Ten years of hard work in JAVA - Bubble sorting algorithm

Bubble sort (bubble)

Core idea: Repeatedly traverse the target array, and compare the sizes of adjacent elements each time it traverses. If the order is wrong, swap the order. until the sorting ends.

Time complexity O(n^2)
twice for loop n*n=n^2
space complexity O(1)
stability (stable)
java code

    public static void bubbleSort(int[] array) {
    
    
        for (int i = 0; i < array.length; i++) {
    
    
            for (int j = 0; j < array.length - 1; j++) {
    
    
                if (array[j] < array[j + 1]) {
    
    
                    //建一个临时值保存 array[j]的值
                    int t = array[j];
                    //array[j] 和array[j+1]交换。相邻的两个值比较大小交互
                    array[j] = array[j + 1];
                    array[j + 1] = t;
                }
            }
        }
    }

Guess you like

Origin blog.csdn.net/weixin_43485737/article/details/133159938