基数排序
pass
1 #include <cstdio> 2 #include <algorithm> 3 using namespace std; 4 int t1[110000],t2[110000],rk[110000],uni[10],c[10]; 5 int n; 6 int get(int *x,int i,int o) 7 { 8 return x[i] / uni[o - 1] % 10; 9 } 10 int main() 11 { 12 scanf("%d",&n); 13 for (int i = 1;i <= n;i++) 14 scanf("%d",&t1[i]); 15 uni[0] = 1; 16 for (int i = 1;i <= 9;i++) uni[i] = uni[i - 1] * 10; 17 int *x = t1,*y = t2; 18 for (int o = 1;o <= 10;o++) 19 { 20 for (int i = 0;i <= 9;i++) c[i] = 0; 21 for (int i = 1;i <= n;i++) c[get(x,i,o)]++; 22 for (int i = 0;i <= 9;i++) c[i] += c[i - 1]; 23 for (int i = n;i >= 1;i--) rk[i] = c[get(x,i,o)]--; 24 for (int i = 1;i <= n;i++) y[rk[i]] = x[i]; 25 swap(x,y); 26 } 27 for (int i = 1;i <= n;i++) 28 printf("%d ",t1[i]); 29 return 0; 30 }
#include <cstdio> #include <algorithm> using namespace std; int tp[110000],sa[110000],vec[110000],uni[10],c[10]; int n; int get(int *x,int i,int o) { return x[i] / uni[o - 1] % 10; } int main() { scanf("%d",&n); for (int i = 1;i <= n;i++) scanf("%d",&vec[i]); uni[0] = 1; for (int i = 1;i <= 9;i++) uni[i] = uni[i - 1] * 10; /* int *x = t1,*y = t2; for (int o = 1;o <= 10;o++) { for (int i = 0;i <= 9;i++) c[i] = 0; for (int i = 1;i <= n;i++) c[get(x,i,o)]++; for (int i = 0;i <= 9;i++) c[i] += c[i - 1]; for (int i = n;i >= 1;i--) rk[i] = c[get(x,i,o)]--; for (int i = 1;i <= n;i++) y[rk[i]] = x[i]; swap(x,y); }*/ for (int i = 1;i <= n;i++) sa[i] = i; for (int o = 1;o <= 10;o++) {//tp[i]表示第二关键排名为i的第一关键字位置 for (int i = 1;i <= n;i++) tp[i] = sa[i]; for (int i = 0; i <= 9; i++) c[i] = 0; for (int i = 1; i <= n; i++) c[get(vec,i,o)]++; for (int i = 1; i <= 9; i++) c[i] += c[i - 1]; for (int i = n; i >= 1; i--) sa[ c[get(vec,tp[i],o)]-- ] = tp[i]; } for (int i = 1;i <= n;i++) printf("%d ",vec[sa[i]]); return 0; }
心之所动 且就随缘去吧