比较简单的一种排序方式。可以再O(n+k)的时间复杂度内将数组排序,n为数组长度,k为数组里最大的数字。
原数组:
| 2 | 1 | 7 | 3 | 5 | 8 | 2 |
统计数组:
| num【i】表示i数字有多少个 | 0 | 1 | 2 | 1 | 0 | 1 | 0 | 1 | 1 |
| 下标 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
排序数组:
| 1 | 2 | 2 | 3 | 5 | 7 | 8 |
#include <algorithm>
#include <iostream>
#include <cstring>
#include <vector>
#include <cstdio>
#include <cmath>
#include <queue>
using namespace std;
const int maxn=1e5+1;
int n;
int A[maxn];
int T[maxn];//辅助数组。
int main(){
scanf("%d",&n);
int k=0; //数组的最大数
for(int i=0;i<n;i++){
scanf("%d",&A[i]);
T[A[i]]++;
if(A[i]>k)k=A[i];
}
for(int i=0,j=0;i<=k;i++){
while(T[i]>0){
A[j++]=i;
T[i]--;
}
}
for(int i=0;i<n;i++){
printf("%d ",A[i]);
}
printf("\n");
return 0;
}