Java資料結構及演算法執行個體:冒泡排序 Bubble Sort_java

來源:互聯網
上載者:User
/**  * 冒泡排序估計是每本演算法書籍都會提到的排序方法。  * 它的基本思路是對長度為N的序列,用N趟來將其排成有序序列。  * 第1趟將最大的元素排在序列尾部,第2趟將第2大的元素排在倒數第二的位置,  * 即每次把未排好的最大元素冒泡到序列最後端。  * 該排序方法實際上分為兩重迴圈,外層迴圈:待排元素從數組的第1個元素開始。  * 內層迴圈:待排元素從數組的第1個元素開始,直到數組尾端未排過的元素。  * 在內迴圈中,如果遇到前面元素比其後的元素大就交換這兩個元素的位置。  * 由此可見冒泡排序的複雜度是O(n^2)  */ package al; public class BubbleSort {   /*    * 冒泡排序 Java語言編寫,可以直接運行 輸入:n個數<a1,a2,,an>    * 輸出:輸入序列的一個排列<a1',a2',,an'>,其中a1'<=a2'<=<=an' 待排的數也稱為key 複雜度:O(n^2) 輸出結果:9    * 10 14 14 21 43 50 77 例子:高矮個站隊    */   public static void main(String[] args) {     BubbleSort bubbleSort = new BubbleSort();     int[] elements = { 14, 77, 21, 9, 10, 50, 43, 14 };     // sort the array     bubbleSort.sort(elements);     // print the sorted array     for (int i = 0; i < elements.length; i++) {       System.out.print(elements[i]);       System.out.print(" ");     }   }   /**    * @author    * @param array    *      待排數組    * @return void    */   public void sort(int[] array) {     int i, j;     int tmp;     for (i = 0; i <= (array.length - 1); i++) { // outer loop       for (j = 0; j < (array.length - 1 - i); j++) { // inner loop         if (array[j] > array[j + 1]) {           tmp = array[j];           array[j] = array[j + 1];           array[j + 1] = tmp;         }       }     }   } } 

聯繫我們

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