冒泡排序

冒泡排序是最基本的排序算法之一,其核心思想是从后向前遍历数组,比较a[i]和a[i-1],如果a[i]比a[i-1]小,则将两者交换。这样一次遍历之后,最小的元素位于数组最前,再对除最小元素外的子数组进行遍历。进行n次(n数组元素个数)遍历后即排好序。外层循环为n次,内层循环分别为n-1, n-2…1次。

时间复杂度: O(n^2)

稳定性:稳定

实现:

   1: /* @brief   bubble sort
   2:  * move the smallest element to the front in every single loop
   3:  */
   4: void
   5: bubble_sort(int a[], int n)
   6: {
   7:     int i, j, tmp;
   8:  
   9:     for (i = 0; i < n; ++i) {
  10:         for (j = n - 1; j > i; --j) {
  11:             if (a[j] < a[j-1]) {
  12:                 tmp = a[j];
  13:                 a[j] = a[j-1];
  14:                 a[j-1] = tmp;
  15:             }
  16:         }
  17:     }
  18: }
posted @ 2012-05-30 19:57  Newerth  阅读(425)  评论(0编辑  收藏  举报