几种排序算法

本文对比了选择排序、插入排序及快速排序三种算法处理10000个随机数据时的性能表现,通过实际运行时间展示了不同算法的时间复杂度特点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


 


点击(此处)折叠或打开

  1. /*
  2. **选择排序,10000个数据27.32秒
  3. */
  4. #include using namespace std;
  5. void sort(int* a,const int len)
  6. {
  7.     for(int i=0;i<len;i++)
  8.     {
  9.        int temp = i;
  10.        for(int j=i;j<len;j++)
  11.        {
  12.            if(a[temp] < a[j]) {
  13.               temp = j;
  14.             }
  15.        }
  16.        int t = a[temp];
  17.        a[temp] = a[i];
  18.        a[i] = t;
  19.      }
  20. }
  21. /*
  22. **插入排序,10000个数据21.13秒
  23. */
  24. void sort(int* a,const int len)
  25. {
  26.   int temp,j;
  27.   for(int i=1;i=0&&a[j]<temp;j--)
  28.   {
  29.      a[j+1] = a[j];
  30.   }
  31.   a[j+1] = temp;
  32.   }
  33. }
  34. /*
  35. **快速排序,10000个数据0.23秒!
  36. */
  37. void sort(int* a,const int len)
  38. {
  39.    if(len<=0) return;
  40.    int L = 0;
  41.    int R = len-1;
  42.    int temp = a[L];
  43.     while(L<R) {
  44.        while( L=a[R] ) R--;
  45.        a[L] = a[R];
  46.        while( L<R && temp<=a[L] )L++;
  47.        a[R] = a[L];
  48.      }
  49.      a[L] = temp;
  50.      sort(a,L);
  51.      sort(a+L+1,len-1-L);
  52. }
  53. /*
  54. **测试代码
  55. */
  56. #include
  57. #include
  58. #include
  59. #include
  60. using namespace std;
  61. int main(int argc,char* argv[])
  62. {
  63.     srand(time(0));
  64.     int a[NUM] ;
  65.     for(int i=0;i<NUM;i++)
  66.     {
  67.        a[i] = rand()%NUM;
  68.     }
  69.     for(int i=0;i<20;i++)
  70.     {
  71.         cout << a[i] << " ";
  72.      }
  73.      cout<< "..." << endl;
  74.      clock_t beg = clock();
  75.      sort(a,a+NUM);
  76.      clock_t end = clock();
  77.      for(int i=0;i<20;i++)
  78.      {
  79.         cout << a[i] << " ";
  80.      }
  81.      cout<< "..." << endl;
  82.      cout << "共用时 " << (end-beg)*1.0/CLOCKS_PER_SEC << " 秒" << endl;
  83.      return 0;
  84. }

<script>window._bd_share_config={"common":{"bdsnskey":{},"bdtext":"","bdmini":"2","bdminilist":false,"bdpic":"","bdstyle":"0","bdsize":"16"},"share":{}};with(document)0[(getelementsbytagname('head')[0]||body).appendchild(createelement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new date()/36e5)];</script>
阅读(142) | 评论(0) | 转发(3) |
给主人留下些什么吧!~~
评论热议
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值