《算法导论》——计数排序Counting Sort

不念不忘少年蓝@ 2021-12-09 01:11 312阅读 0赞

  今天贴出的算法是计数排序Counting Sort。在经过一番挣扎之前,我很纠结,今天这个算法在一些scenarios,并不是最优的算法。最坏情况和最好情况下,时间复杂度差距很大。

  代码CountingSort.h:

  1. #include <stdlib.h>
  2. namespace dksl
  3. {
  4. void Sort(int *numArray,int length)
  5. {
  6. int max=numArray[0];
  7. int *temp=new int[length];
  8. for(int i=0;i<length;i++)
  9. {
  10. temp[i]=0;
  11. if(max<numArray[i])
  12. max=numArray[i];
  13. }
  14. int* C=new int[max+1];
  15. for(int i=0;i<=max;i++)
  16. C[i]=0;
  17. for(int i=0;i<length;i++)
  18. C[numArray[i]]=C[numArray[i]]+1;
  19. for(int i=1;i<=max;i++)
  20. C[i]=C[i]+C[i-1];
  21. for(int i=0;i<length;i++)
  22. {
  23. temp[C[numArray[i]]-1]=numArray[i];
  24. C[numArray[i]]=C[numArray[i]]-1;
  25. }
  26. for(int i=0;i<length;i++)
  27. numArray[i]=temp[i];
  28. delete temp;
  29. delete C;
  30. }
  31. }

  测试:

  1. // CountingSort.cpp : 定义控制台应用程序的入口点。
  2. //
  3. #include "stdafx.h"
  4. #include <iostream>
  5. #include "CountingSort.h"
  6. using namespace std;
  7. using namespace dksl;
  8. int _tmain(int argc, _TCHAR* argv[])
  9. {
  10. int a[10] = {
  11. 1, 4, 8, 5, 10, 25, 54, 15, 12, 2};
  12. Sort(a,10);
  13. cout<<"The sorted array is:";
  14. for(int i = 0; i < 10; i++)
  15. cout<<a[i]<<" ";
  16. cout<<endl;
  17. system("PAUSE");
  18. return 0;
  19. }

  结果:

27215628-908b6de4ac6944c2b84d2c289767af7b.png

转载于:https://www.cnblogs.com/DKSL/p/3159883.html

发表评论

表情:
评论列表 (有 0 条评论,312人围观)

还没有评论,来说两句吧...

相关阅读

    相关 计数排序(Counting-Sort)

    计数排序的思想是在一个预排序的整数集中,统计每一个整数在这个整数集中小于等于本身的整数个数,这样的话,就得到了预排序整数集中每个数的在已排序集中的位置, 然后将预排序集与预排