Java排序算法优化--冒泡排序【温故而知新】

来源:互联网 发布:淘宝客上货软件 编辑:程序博客网 时间:2024/04/30 19:59

对于冒泡排序的改进,感谢MoreWindows(微软最有价值专家),给我提供这么好的思路,我只是写了一个完整的Java版本。

/** * * @author Fly */public class BubbleSort {    //不加思考写的交换排序    //不是冒泡排序,比较的不是相邻的元素    public int[] bubbleSort(int[] a) {        int size = a.length;        for (int i = 0; i < size; i++) {            for (int j = i + 1; j < size; j++) {                if (a[i] > a[j]) {                    int temp = a[i];                    a[i] = a[j];                    a[j] = temp;                }            }        }        return a;    }    //冒泡排序    public int[] bubbleSort1(int[] a) {        int size = a.length;        for (int i = 0; i < size - i; i++) {            for (int j = 0; j < size - i - 1; j++) {                if (a[j] > a[j + 1]) {                    int temp = a[j];                    a[j] = a[j + 1];                    a[j + 1] = temp;                }            }        }        return a;    }    //改进的冒泡排序    //改进点:    //1)增加标志位,标记最终的交换位置,去掉不必要的交换操作;    //2)如果当前循环没有交换数据,说明已经完成排序,去掉不必要的比较;    public int[] bubbleSort2(int[] a) {        int size = a.length;        for (int i = 0; i < size - 1; i++) {            //做一个标志位            int flag = i;            for (int j = 0; j < size - i - 1; j++) {                //如果顺序不对,记录需要交换的标志位,以后一次交换位置                if (a[j] > a[j + 1]) {                    flag = j;                }            }            //如果标志位更换说明数据顺序不对            if (flag > i) {                //交换数据                int temp = a[i];                a[i] = a[flag];                a[flag] = temp;                //调整再次循环起始位置,因为标志位以后的元素(假如有的话)肯定是顺序的                i = flag;            //如果标志位没有变化,那说明数据全部顺位,直接跳出循环            } else {                break;            }        }        return a;    }    public void printArray(int[] a) {        for (int i : a) {            System.out.print(i + ",");        }        System.out.println();    }    public static void main(String[] args) {        int[] a = {2, 3, 1, 5, 7, 8, 9, 0, 11, 10, 12, 13, 14, 4, 6};        BubbleSort bubblesort = new BubbleSort();        bubblesort.printArray(a);        bubblesort.printArray(bubblesort.bubbleSort(a));        bubblesort.printArray(bubblesort.bubbleSort1(a));        bubblesort.printArray(bubblesort.bubbleSort2(a));    }}


0 0
原创粉丝点击