冒泡排序

冒泡排序可能是很多人第一个学的排序算法,思路简单,实现的方式大同小异。

这次收到鸡尾酒排序的启发,尝试用另一种方式来写,感觉更加简单清晰。只要还没排好序,每一趟排序结束后都会产生一个正确的位置,而这时将“数组长度”减1,忽略已经有序的元素。

public static void bubbleSort(int[] A){
    boolean unsorted = true;
    int top = A.length-1;
    while(unsorted){
        unsorted = false;
        for(int i = 0; i < top; i ++){
            if(A[i] > A[i+1]){
                swap(A, i, i+1);
                unsorted = true;
            }
        }
        top --;
    }
}
Java
原文地址:https://www.cnblogs.com/7hat/p/3381308.html