《演算法導論》CLRS演算法C++實現(六)P100 基數排序

來源:互聯網
上載者:User

第八章 線性時間排序

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)進行輔助。

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.