C++实现基数排序

x33g5p2x  于2021-09-24 转载在 C/C++  
字(0.7k)|赞(0)|评价(0)|浏览(429)

  1. #include<iostream>
  2. #include<string.h>
  3. #include<cmath>
  4. using namespace std;
  5. #define MaxSize 100
  6. void RadixSort(int arry[], int size) //对三位数的整形数进行基数排序,size为数组大小
  7. {
  8. int temp[10][MaxSize]; //设置10个箱子,分别表示数字 0~9,每个箱子最多装 MaxSize个数据
  9. int count[10]; //记录每个箱子中的数据个数
  10. memset(temp, 0, sizeof(temp)); //全部初始化为零
  11. memset(count, 0, sizeof(count));
  12. for(int i=0; i<3; ++i) //根据个位、十位、百位分别分配和收集一次,一共三次
  13. {
  14. for(int j=0; j<size; ++j) //分配
  15. {
  16. int p = int(arry[j]/pow(10,i))%10;
  17. temp[p][count[p]] = arry[j];
  18. count[p]++;
  19. }
  20. int m = 0;
  21. for(int j=9; j>=0; --j) //收集
  22. {
  23. for(int q=0; q<count[j]; ++q)
  24. {
  25. arry[m] = temp[j][q];
  26. m++;
  27. }
  28. count[j] = 0; //箱子中的数据收集完后清零
  29. }
  30. }
  31. }
  32. int main()
  33. {
  34. int a[] = {81,94,11,96,12,35,17,95,28,58,41,75,15};
  35. RadixSort(a,13);
  36. for(int i=0; i<13; ++i)
  37. {
  38. cout << a[i] << " ";
  39. }
  40. }

相关文章

最新文章

更多