冒泡排序

原理:
 
data  37 96 8 54

比较相邻两元素,第一次把最小的放在最左边

data  8  96 37 54

第二次在剩下的元素取最小的依次存放

data  8  37 96 54

第三次

data  8  37  54  96

排序完成

空间复杂度为O(1),需要一个临时变量交换用
时间复杂度为O(n 2),适合已经部分排序的数组排序

  1. static int count = 0; //计算次数
  2. void Output(int array[], int n)
  3. {
  4.     printf("%d:/t/t ", count++);
  5.     for (int i=0; i<n; i++)
  6.     {
  7.         printf("%d ", array[i]);
  8.     }
  9.     printf("/n");
  10. }
  11. void swap(int &a, int &b)
  12. {
  13.     printf("%d > %d/n", a, b);
  14.     int temp;
  15.     temp = b;
  16.     b = a;
  17.     a = temp;
  18. }
  19. void BubbleSort(int array[], int n)
  20. {
  21.     for (int i=0; i<n; i++)
  22.     {
  23.         for (int j=i+1; j<n; j++)
  24.         {
  25.             //依次比较,先选出最小的放在最左边
  26.             if (array[i] > array[j])
  27.             {
  28.                 swap(array[i], array[j]);
  29.                 Output(array, n);
  30.             }
  31.             else
  32.                 printf("%d: Do nothing but also do/n", count++);
  33.         }
  34.     }
  35. }
  36. int _tmain(int argc, _TCHAR* argv[])
  37. {
  38.     int array[5] = {37,96,8,54,7};
  39.     Output(array, 5);
  40.     BubbleSort(array, 5);
  41.     printf("****************************************************************************/n");
  42.     count = 0;
  43.     int min_array[5] = {1, 2, 3, 4, 5};
  44.     Output(min_array, 5);
  45.     BubbleSort(min_array, 5);
  46.     printf("****************************************************************************/n");
  47.     count = 0;
  48.     int max_array[5] = {5, 4, 3, 2, 1};
  49.     Output(max_array, 5);
  50.     BubbleSort(max_array, 5);
  51.     return 0;
  52. }
循环次数为n(n-1)/2


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值