排序算法---冒泡排序

来源:互联网 发布:网络市场监管 编辑:程序博客网 时间:2024/06/05 06:56

算法设计:

冒泡排序算法多次遍历数组,在每次遍历中连续比较相邻的元素,如果元素没有按照顺序排列则互换它们的值,否则,保持不变,较小的值逐渐浮向顶部,较大的值逐渐沉下底部。算法时间复杂度为O(n^2)
时间复杂度分析:
在最差情况下,冒泡排序算法需要进行n-1次遍历,第一次要进行n-1次比较,第二次要进行n-2次比较    T(n)=(n-1)+(n-2)+...+2+1        =O(n^2)
算法实现:
public class BubbleSort {    public static void main(String[] args) {        int[] list = { 2, 9, 5, 4, 8, 1, 6 };        bubbleSort(list);        System.out.print("{2,9,5,4,8,1,6}" + " by insertionSort is {");        for (int i : list)            System.out.print(i + ",");        System.out.println("}");    }    public static void bubbleSort(int[] list) {        boolean needNextPass = true;        for (int k = 1; k < list.length && needNextPass; k++) {            needNextPass = false;            for (int i = 0; i < list.length - k; i++) {                if (list[i] > list[i + 1]) {                    int tmp = list[i + 1];                    list[i + 1] = list[i];                    list[i] = tmp;                    needNextPass = true;                }            }        }    }}
原创粉丝点击