图解冒泡排序

615 阅读1分钟

图解

经过一次遍历后,最大的数值将会冒泡到属组最高索引的位置上,下一次,
将会有一个最大的数值冒上来,这种排序算法称为冒泡排序法(bubble sort)

代码:

public static void bubbleSort(int[] data, int n) {
    int sort = 0;
    while (sort < n) {
        for (int i = 0; i < n - sort - 1; i++) {
            if (data[i] > data[i + 1]) {
                swap(data, i, i + 1);
            }
        }
        sort++;
    }
}

private static void swap(int[] data, int i, int j) {
    int temp = data[i];
    data[i] = data[j];
    data[j] = temp;
}

复杂度分析

((n-1)+1)(n-1)/2=n(n-1)/2,故复杂度O(n²)

优化

public static void bubbleSortEnhanced(int [] a, int size){
    boolean  swapped;
    for(int i = 1; i < size; ++i) {
        swapped = false;
        for(int j = 0; j < size - i; ++j) {
            if(a[j] > a[j+1]){
                int t = a[j];
                a[j] = a[j+1];
                a[j+1] = t;
                swapped = true;
            }
        }
        if(!swapped) {
            break;
        }
    }
}

优化之后复杂度最好可为O(n)