#include<iostream>
#include<vector>
using namespace std;
void CountSort(vector<int> A, vector<int> &B, int k,int n)
{
int i,j;
vector<int> C(k+1, 0);
for (i = 0; i < n; i++)
C[A[i]] = C[A[i]] + 1;
for (j = 1; j <= k; j++)
C[j] = C[j] + C[j - 1];
for (j = n-1; j >= 0; j--)
{
B[C[A[j]]] = A[j];
C[A[j]] = C[A[j]] - 1;
}
}
int main(void)
{
vector<int> A = { 2, 5, 3, 0, 2, 3, 0, 3 };
vector<int> B(9, 0); //预留空间大一点,防止边界溢出 因为C[A[j]]不会为0 B从1下标开始
CountSort(A, B, 6, 8);
for (auto i = 1; i < 9;i++)
cout <<B[i] << " ";
cout << endl;
return 0;
}
《算法导论》中的计数排序的C++实现
最新推荐文章于 2022-07-27 17:40:47 发布