Eight sorting algorithms - bubble sorting (moving picture understanding)

Bubble Sort

Algorithm ideas

The principle of bubble sorting is: from left to right, adjacent elements are compared. Each round of comparison, either the largest one or the smallest one in the sequence is found. This number will emerge from the far right of the sequence.

Taking sorting from small to large as an example, after the first round of comparison, the largest number among all numbers will float to the far right; after the second round of comparison, the second largest number among all numbers will float to the second last positions... just compare round after round, and finally achieve sorting from small to large.
 

animation

 

algorithm code

 public static void bubbleSort(int[] a){
    for (int i = 0; i < a.length-1; i++) {//a.length-1是因为不用与自己比较,所以比的数就少一个
         for (int j = 0; j < a.length-1-i; j++){//a.lenght-1-i是因为每一趟就会少一个数比较
             if(a[j]>a[j+1]){
                  int tmp = a[j];
                  a[j] = a[j+1];
                  a[j+1]  = tmp;
             }
         }
     }
  }

The above code still has some deficiencies, if a sequence is already ordered, or it is already sorted in the middle of the sort. But the bubble sort will still go through two for loops, and the time complexity is always O(n^2) . For this reason, we can improve the code, add a flag before each comparison , if the number is exchanged, change the flag, indicating that the sequence is not in order. If the flag does not change after a comparison, it means that the sequence is already in order, and there is no need to loop again. At this time, the time complexity can best be changed to O(n) .

Optimized

 public static void bubbleSort(int[] a){

        for (int i = 0; i < a.length-1; i++) {
            int flag = 0;  //添加标记
            for (int j = 0; j < a.length-1-i; j++) {
                if(a[j]>a[j+1]){
                    int tmp = a[j];
                    a[j] = a[j+1];
                    a[j+1]  = tmp;
                    falg++;
                }
            }
            if(flag==0) break; //即falg在经过for循环后,还为0 说明已排好序了,就不用再进行排序
        }                      
    }

Complexity Analysis

Time complexity  O(n^2) After optimization, the best case becomes o(n)

time complexity test

Next, let's try to test it with a lot of data.

int[] a = new int[10_0000]; //100,000 data test

1. The orderArray function is implemented to generate a basic ordered sequence, that is, arranged from small to large.

public static void orderArray(int[] a) {
        for (int i = 0; i < a.length; i++) {
            a[i] = i;
        }
 }

2. The notOrderArray function generates a reverse sequence, that is, arranged from largest to smallest.

public static void notOrderArray(int[] a) {
        for (int i = 0; i < a.length; i++) {
            a[i] = a.length-i;
        }
}

3. The randomArray function generates a random unordered array.

 public static void randomArray(int[] a) {
        Random random = new Random();
        for (int i = 0; i < a.length; i++) {
            a[i] = random.nextInt(10_0000);
        }
 }

4. The testInsertSort function tests the return value of System.currentTimeMillis() in milliseconds.

 public static void testInsertSort(int[] a){
        int[] tmpArray = Arrays.copyOf(a,a.length);
        long startTime = System.currentTimeMillis();    //注意用long接收
        shellSort(tmpArray);
        long endTime = System.currentTimeMillis();  //返回单位是毫秒
        System.out.println("冒泡排序耗时:"+(endTime-startTime));
 }

5. Main function call execution

public static void main(String[] args) {
 
 
        int[] a = new int[10_0000];
        //有序
        System.out.println("基本有序数列");
        orderArray(a);
        testInsertSort(a);
 
        //倒序
        System.out.println("逆序数列");
        notOrderArray(a);
        testInsertSort(a);
 
        //随机乱序
        System.out.println("无序数列");
        randomArray(a);
        testInsertSort(a);
 
}

operation result

    

 By comparison, it is found that the time complexity after the improvement is still reduced.

full code

import java.util.Random;

public class sort {

    public static void main(String[] args) {
    
        int[] a = new int[10_0000];
        
        //有序
        System.out.println("基本有序数列");
        orderArray(a);
        testInsertSort(a);

        //无序
        System.out.println("逆序数列");
        notOrderArray(a);
        testInsertSort(a);

        //乱序
        System.out.println("无序数列");
        randomArray(a);
        testInsertSort(a);

    }


    //冒泡排序
    //时间复杂度 O(n^2)   优化后 最好情况 O(n)
    public static void bubbleSort(int[] a){
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a.length-1-i; j++) {
                if(a[j]>a[j+1]){
                    int tmp = a[j];
                    a[j] = a[j+1];
                    a[j+1]  = tmp;
                }
            }
        }
    }


    //优化后的冒泡排序
    public static void bubbleSort1(int[] a){

        for (int i = 0; i < a.length; i++) {
            int flag = 0;
            for (int j = 0; j < a.length-1-i; j++) {
                if(a[j]>a[j+1]){
                    int tmp = a[j];
                    a[j] = a[j+1];
                    a[j+1]  = tmp;
                    flag++;
                }
            }
            if(flag==0) break;
        }
    }


    //生成有序数组  从小到大排列
    public static void orderArray(int[] a) {
        for (int i = 0; i < a.length; i++) {
            a[i] = i;
        }
    }


    //n无序 其实就是从大到小排列
    public static void notOrderArray(int[] a) {
        for (int i = 0; i < a.length; i++) {
            a[i] = a.length-i;
        }
    }

    //乱序 随机生成序列
    public static void randomArray(int[] a) {
        Random random = new Random();
        for (int i = 0; i < a.length; i++) {
            a[i] = random.nextInt(10_0000);
        }
    }

    //大量数据测试
    public static void testInsertSort(int[] a){
        int[] tmpArray = Arrays.copyOf(a,a.length);
        long startTime = System.currentTimeMillis();    //注意用long接收
        bubbleSort1(tmpArray);
        long endTime = System.currentTimeMillis();
        System.out.println("改进冒泡排序耗时:"+(endTime-startTime));
    }

}

It is not easy to create, if this blog is helpful to you, please remember to leave a message + like it.

Guess you like

Origin blog.csdn.net/m0_73381672/article/details/132028979