码迷,mamicode.com
首页 > 编程语言 > 详细

冒泡排序

时间:2015-12-27 15:57:08      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

冒泡排序  最佳时间复杂度O(n),最差时间复杂度O(n2)

public class BubbleSort {

    /**
     * @param args
     */
    public static void main(String[] args) {

        // TODO Auto-generated method stub
        int[] a = { 2, 3, 2, 5, 6, 1, -2, 3, 14, 12 };
        bubbleSort2(a);
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + " ");
        }
    }

    private static void bubbleSort(int[] a) {

        boolean needNextPass = true;
        for (int i = 1; i < a.length && needNextPass; i++) {
            // Array may be sorted and next pass not needed
            needNextPass = false;
            for (int j = 0; j < a.length - i; j++) {
                if (a[j] > a[j + 1]) {
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                    needNextPass = true;
                }
            }
        }
    }

    private static void bubbleSort2(int[] a) {

        boolean needNextPass = true;
        for (int i = a.length - 1; i > 0 && needNextPass; i--) {
            // Array may be sorted and next pass not needed
            needNextPass = false;
            for (int j = 0; j < i; j++) {
                if (a[j] > a[j + 1]) {
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                    needNextPass = true;
                }
            }
        }
    }
}

 

冒泡排序

标签:

原文地址:http://www.cnblogs.com/diyishijian/p/5080062.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!