Java排序演算法最佳化--冒泡排序【溫故而知新】

來源:互聯網
上載者:User

對於冒泡排序的改進,感謝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));    }}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.