冒泡排序法—-Java實現

來源:互聯網
上載者:User

冒泡排序(BubbleSort)

1、思想

通過無序區中相鄰記錄關鍵字間的比較和位置的交換,使關鍵字最小的記錄如氣泡一般逐漸往上“漂浮”直至“水面”。 

 

2、時間複雜度  

最好情況下:正序有序,則只需要比較n次。故,為O(n)  
最壞情況下:  逆序有序,則需要比較(n-1)+(n-2)+……+1,故,為O(N*N)

 

3、穩定性  

排序過程中只交換相鄰兩個元素的位置。因此,當兩個數相等時,是沒必要交換兩個數的位置的。所以,它們的相對位置並沒有改變,冒泡排序演算法是穩定的!

 

4、實現

 

public class BubbleSort {

 

/**

* @param args

*/

public static void main(String[] args) {

int[] data = { 49, 38, 65, 97, 76, 13, 27, 9 };

bubbleSort(data, 0, data.length - 1); // 第一種實現方式

printData(data);

}

 

public static void bubbleSort(int [] data ,int low ,int high){

if(low>=high){

return ;

}

for(int i =low ;i<high;i++){

for(int j=high;j>i;j--){

if(data[i]>data[j]){

swap(data, i, j);

}

}

}

}

 

public static void swap(int[] data, int i, int j) {

int temp = data[i];

data[i] = data[j];

data[j] = temp;

}

 

public static void printData(int[] data) {

for (int i : data) {

System.out.print(i + " ");

}

}

 

}

相關文章

聯繫我們

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