排序演算法之冒泡排序

來源:互聯網
上載者:User

標籤:style   blog   color   io   for   re   

對於大多數學電腦的人來說,冒泡排序應該都是接觸的第一種排序方式,冒泡排序的排序思想是比較簡單的,

它的演算法的是:
  1. 比較相鄰的元素。如果第一個比第二個大,就交換他們兩個。
  2. 對每一對相鄰元素作同樣的工作,從開始第一對到結尾的最後一對。在這一點,最後的元素應該會是最大的數。
  3. 針對所有的元素重複以上的步驟,除了最後一個。
  4. 持續每次對越來越少的元素重複上面的步驟,直到沒有任何一對數字需要比較。

     

    冒泡排序的實現如下:

     1 #include<stdio.h> 2 int main() 3 { 4     int array[] = {3, 5, 2, 6, 4, 1}; 5     int count = sizeof(array) / sizeof(array[0]); 6     int i, j; 7     for(i = 0; i < count - 1; i++) { 8         for(j = 0; j < count - 1 - i; j++) { 9             if (array[j] > array[j + 1]) {10                 int temp = 0;11                 temp = array[j];12                 array[j] = array[j + 1];13                 array[j + 1] = temp;14             }15         }16     }17     for(i = 0; i < count; i++) {18         printf("%d\n", array[i]);19     }20 21 22 23 24 25     return 0;26 }

     

    其實冒泡排序還可以最佳化,就是當比較和交換過程中數組已經有序的情況,這樣的話就不用再進行冒泡了,所以冒泡排序可以這樣最佳化:

     1 #include<stdio.h> 2 int main() 3 { 4     int array[] = {3, 5, 2, 6, 4, 1}; 5     int count = sizeof(array) / sizeof(array[0]); 6     int i, j; 7     int flag = 1; 8     for(i = 0; i < count - 1 && 1 == flag; i++) { 9         flag = 0;10         for(j = 0; j < count - 1 - i; j++) {11             if (array[j] > array[j + 1]) {12                 int temp = 0;13                 temp = array[j];14                 array[j] = array[j + 1];15                 array[j + 1] = temp;16                 flag = 1;17             }18         }19     }20     for(i = 0; i < count; i++) {21         printf("%d\n", array[i]);22     }23 24     return 0;25 }

     

聯繫我們

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