常见排序算法之计数排序的C++实现
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution
{
public:
vector<int> countSort(vector<int>& v)
{
int size = v.size();
if (size <= 1)
return v;
int min = v[0], max = v[0];
for (int i = 1; i < size; ++i)
{
if (min > v[i])
min = v[i];
if (max < v[i])
max = v[i];
}
vector<int> vcount(max - min + 1, 0);
for (int i = 0; i < size; ++i)
++vcount[v[i] - min];
v.clear();
for (int i = 0; i < vcount.size(); ++i)
{
for (int j = 0; j < vcount[i]; ++j)
v.push_back(min + i);
}
return v;
}
};
int main()
{
Solution so;
vector<int> v1 = { 0, 1, 0, 1, 2, 2, 3, 1, 0, 1, 2, 3, 1, 2, 3 };
for (int x : v1)
cout << x << " ";
cout << endl;
so.countSort(v1);
for (int x : v1)
cout << x << " ";
return 0;
}