/* Sample: 计数排序
* 计数排序是一种运行时间在输入的某种假设情况下可以为 O(n) 的算法,它的过程中没有比较环节。
* 计数排序法是一种简单的排序方法,这种排序算法对一个待排序的数组进行排序,并将排序结果放到另一个新的数组中。
* 计数排序算法针对待排序数组中的每个记录,扫描待排序的数组一趟,统计待排序数组中有多少个记录的值比该记录的值小。
* 假设针对某一个记录,统计出的计数值为c,那么,这个记录在新的有序数组中的合适的存放位置即为c。
*/
#include
using namespace std;
//其中inputArr为输入,outputArr为输出,inputLen为元素个数,maxKey为最大元素
void CountSort(int inputArr[], int outputArr[], int inputLen, int maxKey)
{
int j;
int *c = new int[maxKey+1];
memset(c, 0, (maxKey+1) * sizeof(int));
for (j = 0; j < inputLen; j++)
{
c[inputArr[j]]++; //求出重复的数字出现多少次
}
for (j = 1; j <= maxKey; j++)
{
c[j] += c[j - 1]; //求出不比数字j大的元素的个数,包括相等的
}
for (j = inputLen - 1; j >= 0; j--) //注意此处不能写成for(int j = 0; j < inputLen; j++),否则会造成排序算法的不稳定
{
outputArr[c[inputArr[j]] - 1] = inputArr[j];
c[inputArr[j]]--;
}
delete []c;
}
int main(int argc, char* argv[])
{
int srcArr[] = {4,1,5,2,8,4};
int len = 6;
int maxKey = 8;
int* retArr = new int[len];
CountSort(srcArr, retArr, len, maxKey);
for(int i = 0; i < len; i++)
{
cout<
}
cout<
system("pause");
return 0;
}
/*
Output:
1 2 4 4 5 8
请按任意键继续. . .
*/