《算法导论》CLRS算法C++实现(六)P100 基数排序

来源:互联网 发布:产后护理软件 编辑:程序博客网 时间:2024/04/30 07:05

第八章 线性时间排序

8.3 基数排序

算法导论上对基数排序的算法描述只有两行。。。 微言大义的说。。。

RADIX-SORT(A, d)

1 for i ← 1 to d2     do use a stable sort to sort array A on digit i

C++代码

 1 #include <iostream> 2  3 using namespace std; 4  5 //求数组中数字的最大位数 6 int maxDigit(int* arr,int digit) 7 { 8     int n = 0; 9     int* temp = new int[digit];10     for(int i = 0; i < digit; i++)11         temp[i]= arr[i];12     for(int i = 0; i < digit; i++)13     {14         int counter =1;15         while(temp[i] / 10 > 0)16         {17             counter++;18             temp[i] /= 10;19         }20         if(n < counter)21             n = counter;22     }23     delete[] temp;24     return n;25 }26 27 //基数排序28 void radixSort(int* arr, int digit)29 {30     int n = maxDigit(arr, digit);31     int* temp = new int[digit];32     int* count = new int[10];33     int i, j, k;34     int radix = 1;35     for(i = 1; i <= n; i++)36     {37         for(j = 0; j < 10; j++)38             count[j] = 0;39         for(j = 0; j < digit; j++)40         {41             k = (arr[j] / radix) % 10;42             count[k]++;43         }44         for(j = 1; j < 10; j++)45             count[j] = count[j-1] + count[j];46         for(j = digit - 1; j >= 0; j--)47         {48             k = (arr[j] / radix) % 10;49             count[k]--;50             temp[count[k]] = arr[j];51         }52         for(j = 0; j < digit; j++)53             arr[j] = temp[j];54         radix *= 10;55     }56     delete[] temp;57     delete[] count;58 }59 60 int main()61 {62     int a[] = {22, 34, 95, 87, 56, 980, 12, 48};63     radixSort(a, 8);64     for(int i = 0; i < 8; i++)65     {66         cout << a[i] << " ";67     }68     cout << endl;69     return 0;70 }

在C++实现中,我使用了一个辅助的函数 int maxDigit(int* arr,int digit)来计算待排序数组中最大的数位,以使程序有更大的适用范围,不需要待排序的数字位数相同。

基数排序的算法很直观。在一个数组中,每个元素都有d位数字,其中第1位是最低位,第d位是最高位。依次判断每个位置的排序。基数排序需要另一种稳定的排序算法(stable sort)进行辅助。

 

原创粉丝点击