冒泡排序(java)

來源:互聯網
上載者:User

標籤:位置   current   mat   測試   sort   http   system   排序   creat   

冒泡排序的思想就是將相鄰的兩個元素做一次比較, 比較出如果後面元素比前面元素小就交換一次位置;

經過一趟這樣的交換最大的元素就落在了最後面, 所以內層迴圈的邊界也出來了,就是不算經排序後的最後的幾個元素 ,即 n - i -  1;

而外層迴圈所需要比較到的位置也就是n - 2, 如果超過了則超過了邊界;(其中n 是元素的總個數)

例如有這樣一列數:

38、49、65、76、13、27、30、97

每趟經過排序如下:

下面是冒泡排序的演算法:

public class BubbleSort {    public int[] sort(int[] arrays) {        int temp = 0;        for (int i = 0; i < arrays.length - 2; i++) {            for (int j = 0; j < arrays.length - 1 - i; j++) {                if (arrays[j] > arrays[j + 1]) {                    temp = arrays[j];                    arrays[j] = arrays[j + 1];                    arrays[j + 1] = temp;                }            }        }        return arrays;    }}

測試類別如下:

public class Test {    public static void main(String[] args) {        BubbleSort bubbleSort = new BubbleSort();        int[] array = createArray();        long ct1 = System.currentTimeMillis();        int[] arrays = bubbleSort.sort(array);        long ct2 = System.currentTimeMillis();        display(arrays);                System.out.println("所消耗的時間:" + (ct2 - ct1));            }    public static void display(int[] arrays) {        System.out.println("排序後資料:");        for (int i = 0; i < arrays.length; i++) {            System.out.print(arrays[i] + "\t");            if (i % 10 == 0) {                System.out.println();            }        }        System.out.println();    }    public static int[] createArray() {        int[] array = new int[10000];        System.out.println("數組中元素是:");        for (int i = 0; i < 10000; i++) {            array[i] = (int) (Math.random() * 1000);            System.out.print(array[i] + "\t");            if (i % 10 == 0) {                System.out.println();            }        }        System.out.println();        return array;    }}

10000個數經過冒泡排序的時間大約是200ms,而十萬個數經過排序的時間大約就是14000ms,由此可見資料量很大條件下冒泡排序的局限性;

 

冒泡排序(java)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.