Counting sort 计数排序

转载自


http://blog.youkuaiyun.com/joker0910/article/details/6278668

个人感觉,这个更像是索引排序:

 

这是一篇分析的  文章  :

 

我的实现:

 

 

  1. /* 
  2. *作者: JoKer  
  3. *时间:2011.3.25  
  4. *作用:线性排序,时间复杂度O(n) 
  5. *    这是一种非比较排序,所以速度比较快,但是有限制条件的  
  6. *   这个算法要求数组中的元素全是在已知范围的集合中,这里假设从0 到 dif_num的整数。 
  7. * 
  8. */  
  9. #include <iostream>  
  10. using namespace std;  
  11. int counting_sort( int* array, int dif_num, int len)  
  12. {  
  13.     int* index = new int[dif_num + 1];  
  14.     int* output = new int[len];  
  15.     int  i = 0;  
  16.     if(index == NULL)  
  17.     {  
  18.         cout << "alloc failed !" << endl;  
  19.         getchar();  
  20.         exit(0);  
  21.     }  
  22.     if(output == NULL)  
  23.     {  
  24.         cout << "alloc failed!!!" << endl;  
  25.         getchar();  
  26.         exit(0);  
  27.     }  
  28.     memset (index, 0, sizeof(int) * (dif_num + 1));  
  29.     memset (output, 0, sizeof(int) * len);  
  30.     for (i = 0; i < len; i++)  
  31.     {  
  32.         index[array[i]]++;  
  33.     }  
  34.       
  35.     for (i = 1; i < dif_num + 1; i++)  
  36.     {  
  37.         index[i] = index[i] + index[i-1];  
  38.     }  
  39.     for (i = 0; i < len; i++)  
  40.     {  
  41.         int n_index = --index[array[i]];  
  42.         output[n_index] = array[i];  
  43.     }  
  44.     for (i = 0; i < len; i++)  
  45.     {  
  46.         cout << output[i] << " " ;  
  47.     }  
  48.     return 0;  
  49. }  
  50. int main()  
  51. {  
  52.     int array[10] = {3,5,3,5,1,2,6,7,8,3};  
  53.     counting_sort(array, 8, 10);  
  54.     getchar();  
  55.     return 0;  
  56. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值