#include "stdafx.h"
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<map>
using namespace std;
void pause() {
getchar(), getchar();
}
const int N = 1e5;
int a[N];
int count_sort(vector<int> &arr) {
for (int &x : arr) {
if (x < 0 || x >= N) return 0;
a[x]++;
}
int j = 0;
for (int i = 0; i < N; ++i) {
while (a[i]--) arr[j++] = i;
}
return 1;
}
int count_sort2(vector<int> & arr) {
int mi = 0x7f, ma = -0x7f;
for (int &x : arr) {
if (x < 0 || x >= N) return 0;
mi = min(mi, x), ma = max(ma, x);
}
int len = ma - mi + 1;
vector<int>bucket(len);
for (int &x: arr) bucket[x-mi]++;
int j = 0;
for (int i = 0; i < len; ++i) {
while (bucket[i]--) arr[j++] = i + mi;
}
return 1;
}
int main() {
vector<int> arr = { 8,9999,22,1,45,22,1,0,9,333333 };
if (count_sort2(arr)) {
for (int x : arr) {
cout << x << " ";
}
}
else {
puts("输入数不符合规范");
}
pause();
return 0;
}
计数排序简单实现
最新推荐文章于 2022-04-20 17:00:15 发布