1、冒泡排序优化思想

在文章《JAVA实现冒泡排序算法》中,我们用常规算法实现了冒泡排序,在此篇中,我们对冒泡排序算法进行优化,思想如下:引入一个标志位,默认为true,如果本次或者本趟遍历前后数据比较发生了交换,则标志位设置为true,否则为false;直到又一次数据没有发生交换,说明排序完成。

2、实例

(1)java代码

text
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
package cn.com.yy;

import java.util.Random;

public class BubbleSortClient {
    
    public static void main(String[] args) {
        
        //构造数据
        int[] arr = constructDataArray(15);
        System.out.println("---------排序前-----------");
        printArrayData(arr);
        //冒泡排序
        bubbleSort4(arr);
        System.out.println("---------排序后-----------");
        printArrayData(arr);
    }
    
    //构造数据
    public static int[] constructDataArray(int length){
        int[] arr = new int[length];
        Random random = new Random();
        for(int i=0;i<length;i++){
            arr[i] = random.nextInt(length);
        }
        return arr;
    }
    
    /**
     * 引入标志位,默认为true
     * 如果前后数据进行了交换,则为true,否则为false。如果没有数据交换,则排序完成。
     * @param arr
     */
    public static int[] bubbleSort4(int[] arr){
        boolean flag = true;
        int n = arr.length;
        while(flag){
            flag = false;
            for(int j=0;j<n-1;j++){
   if(arr[j] >arr[j+1]){
       //数据交换
       int temp = arr[j];
       arr[j] = arr[j+1];
       arr[j+1] = temp;
       //设置标志位
       flag = true;
   }
            }
            n--;
        }
        return arr;
    }
    
    //打印数据
    public static void printArrayData(int[] arr){
        for(int d :arr){
            System.out.print(d + "   ");
        }
        System.out.println();
    }
}

(2)结果

text
1 2 3 4 5
---------排序前-----------
10   3   9   10   7   1   6   8   12   8   7   14   14   8   1   
---------排序后-----------
1   1   3   6   7   7   8   8   8   9   10   10   12   14   14   

原文地址:https://blog.csdn.net/yyywyr/article/details/38376369?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168474999716782427485144%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=168474999716782427485144&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-14-38376369-null-null.142^v87^insert_down1,239^v2^insert_chatgpt&utm_term=java%E4%BC%98%E5%8C%96