基数排序
通过对个位-十位-百位……的排序得出结果 复杂度约为 O(P(N+B)) 其中 P是排序的趟数 N是元素个数 B是筒数(这里B=10)
代码如下:
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 int data[19] = {16156,121,51,23,13,15,13,1,51,32,156,13,1,21,65,16,413,21,3}; 6 int n = 19; 7 8 int len() 9 { 10 int maxx = 0; 11 for(int i=0; i<n; i++) 12 if(maxx< (int)log10(data[i])+1) 13 maxx = (int)log10(data[i])+1; 14 return maxx; 15 } 16 17 void sort() 18 { 19 int *cmp = new int[n]; 20 int *q = new int[10]; 21 int cnt = 1; 22 for(int i=0; i<len(); i++) 23 { 24 for(int j=0;j<10;j++) 25 q[j] = 0; 26 for(int j=0; j<n; j++) 27 q[data[j]/cnt%10]++; 28 for(int j=1; j<10; j++) 29 q[j] = q[j-1]+q[j]; 30 for(int j=n-1; j>=0; j--) 31 { 32 cmp[q[data[j]/cnt%10]-1] = data[j]; 33 q[data[j]/cnt%10]--; 34 } 35 for(int j=0; j<n; j++) 36 data[j] = cmp[j]; 37 cnt*=10; 38 } 39 delete []cmp; 40 delete []q; 41 return ; 42 } 43 44 int main() 45 { 46 sort(); 47 for(int i=0; i<n; i++) 48 cout<<data[i]<<" "; 49 cout<<endl; 50 return 0; 51 }