第八章 線性時間排序
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)進行輔助。