排序算法学习——冒泡排序

冒泡排序是比较容易理解的一种稳定排序方法,我们将记录关键字的顺序表elem[0……n-1]看作垂直排列,每个记录看作是重量为elem[i]的气泡。根据重气泡不能在轻的气泡上的原则,从上往下扫描,把重气泡下沉,轻气泡上浮。这样,我们便能得到一个有序的顺序表了,具体代码如下:

 1 template <typename ElemType>
 2 void bubbleSort(ElemType elem[],int len)
 3 {
 4     if(NULL == elem)
 5         return;
 6     int i,j,k;
 7     ElemType temp;
 8     for(i=len-1;i>0;i--)
 9     {
10           for(j=0;j<i;j++)
11           {
12                if(elem[j]>elem[j+1])
13               {
14                      temp = elem[j];
15                      elem[j]=elem[j+1];
16                      elem[j+1]=temp;
17               } 
18           }
19     }
20 }                

下面是测试效果

 1 #include<windows.h>
 2 #include<iostream>
 3 using namespace std;
 4 int main()
 5 {
 6     int arr[10];
 7     srand(unsigned int(time_t(NULL)));//随机数种子
 8     for(int i=0;i<10;i++)
 9     {
10         arr[i]=rand()%10;//0-10内的整数
11                 cout<<arr[i]<<"  ";
12     }
13     cout<<endl;
14     long time_start = GetTickCount();
15     bubbleSort(arr,10);
16     long time_stop = GetTickCount();
17         for(int i=0;i<10;i++)
18     {
19                 cout<<arr[i]<<"  ";
20     }
21         cout<<endl;
22     cout<<"Time cost:"<<time_stop - time_start<<endl;
23     return 0;
24 }  

 

数据量小,时间忽略不计!

 

转载于:https://www.cnblogs.com/fclz/p/3367393.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值