这是一种不稳定的排序
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> CountSort(const vector<int> & vecNum)
{
vector<int> vecNumSort;
if (vecNum.empty()) return vecNumSort;
vector<int> vecCount;
int nJizhi = 0;
int nSize = 0;
int nMax = vecNum[0];
int nMin = vecNum[0];
for (auto itr=vecNum.begin();
itr!=vecNum.end();
++itr)
{
if (nMax < *itr) nMax = *itr;
if (nMin > *itr) nMin = *itr;
}
nJizhi = nMin;
nSize = nMax - nMin + 1;
vecCount.assign(nSize, 0);
for (auto itr=vecNum.begin();
itr!=vecNum.end();
++itr)
{
vecCount[*itr-nJizhi] += 1;
}
for (int i=0; i<vecCount.size(); ++i)
{
for (int j=0; j<vecCount[i]; ++j) {
vecNumSort.push_back(i+nJizhi);
}
}
return vecNumSort;
}
void Output(int a)
{
cout << a << " ";
}
int main(int argc, char ** argv)
{
const int LEN = 8;
int a[LEN] = {2, 5, 3, 1, 2, 3, 1, 3};
vector<int> vecNum(a, a+LEN);
for_each(vecNum.begin(), vecNum.end(), Output);
cout << endl;
vecNum = CountSort(vecNum);
for_each(vecNum.begin(), vecNum.end(), Output);
cout << endl;
return 0;
}
网友评论