思路參考《算法導論》P110html
另外,這位老哥講的很不錯:http://www.cnblogs.com/kkun/archive/2011/11/23/2260275.htmlios
-------------------------------------------------------------------代碼-------------------------------------------------------------------算法
1 // 基數排序.cpp: 定義控制檯應用程序的入口點。 2 // 3 4 #include "stdafx.h" 5 #include <iostream> 6 #include <vector> 7 #include <math.h> 8 9 using namespace std; 10 11 int RADIX(vector<int> &A,int d)//出於簡單考慮,咱們假設A中全部的數都是d位 12 { 13 vector<vector<int>> bucket(10);//用二維數組也行 14 int temp; 15 for (int i = 0; i < d; i++) 16 { 17 for (int j = 0; j < A.size(); j++) 18 { 19 temp = (int)(A[j] / pow(10, i)) % 10; 20 bucket[temp].push_back(A[j]); 21 } 22 int ptr = 0; 23 for (int i = 0; i < 10; i++) 24 { 25 for (int j = 0; j < bucket[i].size(); j++) 26 { 27 A[ptr++] = bucket[i][j]; 28 } 29 bucket[i].erase(bucket[i].begin(), bucket[i].end()); 30 } 31 } 32 return 0; 33 } 34 35 int main() 36 { 37 vector<int> A = {329,457,657,839,436,720,355}; 38 for (auto c : A) 39 cout << c << ends; 40 cout << endl; 41 42 RADIX(A,3); 43 for (auto c : A) 44 cout << c << ends; 45 cout << endl; 46 return 0; 47 }
運行結果以下:數組