(1.3.6.1)线性排序:基数排序

来源:互联网 发布:算法统宗圆中正方形 编辑:程序博客网 时间:2024/06/14 12:59

前言

当序列中元素范围比较大时,就不适合使用计数排序。针对这种情况,就有了基数排序(Radix Sort),这是一种按位排序。它仍然是以计数排序为基础。

基数排序

基数排序的基数:十进制数的基数自然是10,二进制的基数自然是2。通常有两种按位排序策略:1.高位优先法(most significant digit first,MSD):简单讲就是从高位排起。2.低位优先法(least significant digit first,LSD):它与高位优先相反,从低位排起。从排序效果上看,高位优先比较直观,但却涉及到递归的过程,故最常用的还是低位优先法。说它以计数排序为基础,理由如下,以最常见的十进制数为例:


仔细理解上图,高位优先的过程你也一定可以推测出来。下面给出低位优先下的代码。

代码

[cpp] view plaincopy
  1. #include<iostream>  
  2. #include<iomanip>  
  3. using namespace std;  
  4. //获取最大位数  
  5. int get_max_digit(int array[], int n)  
  6. {  
  7.     int digit, max;  
  8.     digit = 0;  
  9.     max = array[0];  
  10.     for (int i = 1; i < n; i++)  
  11.     {  
  12.         if (array[i] > max)  
  13.             max = array[i];  
  14.     }  
  15.     while (max)  
  16.     {  
  17.         digit++;  
  18.         max /= 10;  
  19.     }  
  20.     return digit;  
  21. }  
  22. //基数排序  
  23. void RadixSort(int array[], int n)  
  24. {  
  25.     //创建临时数组  
  26.     int *temp = new int[n];  
  27.     //位数:决定了排序趟数  
  28.     int digit = get_max_digit(array, n);  
  29.     //计数数组  
  30.     int count[10];  
  31.     //排序  
  32.     int r, i, d;  
  33.     for (r = 1; r <= digit; r++)  
  34.     {  
  35.         //重置计数数组  
  36.         memset(count, 0, 10 * sizeof(int));  
  37.         //把数据存储到临时数组  
  38.         memcpy(temp, array, n*sizeof(int));  
  39.         d = i = 1;  
  40.         while (i < r)  
  41.         {  
  42.             i++;  
  43.             d *= 10;  
  44.         }  
  45.         for (i = 0; i < n; i++)  
  46.             count[(array[i] / d) % 10]++;  
  47.         for (i = 1; i < 10; i++)  
  48.             count[i] += count[i - 1];  
  49.         //数据回放  
  50.         for (i = n - 1; i >= 0; i--)  
  51.             array[--count[(temp[i] / d) % 10]] = temp[i];  
  52.     }  
  53. }  
  54. void print(int array[], int n)  
  55. {  
  56.     for (int i = 0; i < n; i++)  
  57.         cout << setw(6) << array[i];  
  58.     cout << endl;  
  59. }  
  60. int main()  
  61. {  
  62.     cout << "******基数排序***by David***" << endl;  
  63.     int array[] = { 123, 234, 45, 111, 6, 128 };  
  64.     int n = sizeof(array) / sizeof(int);  
  65.     cout << "原序列" << endl;  
  66.     print(array, n);  
  67.     cout << "基数排序" << endl;  
  68.     RadixSort(array, n);  
  69.     print(array, n);  
  70.     system("pause");  
  71.     return 0;  
  72. }  

运行    



0 0