一种以map为容器,红黑树为底层逻辑的高效排序
时间复杂度:
空间复杂度:
先看代码:
#include<bits/stdc++.h>
using namespace std;
int n;
map<int,int> t;
int main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
cin>>n;
while(n--){
int x;
cin>>x;
t[x]++;
}
for(auto p:t)
while(p.second--)
cout<<p.first<<' ';
return 0;
}例如序列 5,4,3,5,4,2,1,在map中存为:
| 键 | 值 |
|---|---|
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 2 |
按值输出键即可
缺点:常数较大,时间复杂度和空间复杂度明显低于sort排序与归并排序、快速排序
优点:比较高效,巧用map容器的自动插入、默认初始值的性质,结合计数排序思路,避免值域内无效访问,得到大幅的提升。