计数排序假设n个输入元素中的每一个都介于0和k之间的整数,k为n个数中最大的元素。当k=O(n)时,计数排序的运行时间为θ(n)。计数排序的基本思想是:对n个输入元素中每一个元素x,统计出小于等于x的元素个数,根据x的个数可以确定x在输出数组中的最终位置。此过程需要引入两个辅助存放空间,存放结果的B[1...n],用于确定每个元素个数的数组C[0...k]。算法的具体步骤如下:
(1)根据输入数组A中元素的值确定k的值,并初始化C[1....k]= 0;
(2)遍历输入数组A中的元素,确定每个元素的出现的次数,并将A中第i个元素出现的次数存放在C[A[i]]中,然后C[i]=C[i]+C[i-1],在C中确定A中每个元素前面有多个元素;
(3)逆序遍历数组A中的元素,在C中查找A中出现的次数,并结果数组B中确定其位置,然后将其在C中对应的次数减少1。
#include<iostream>
using namespace std;
void count_sort(int a[], int b[], int k, int length)
{
int i, j;
//each element in A between 0 and k [0,k],total k+1 elements;
// int *c = new int[k + 1];
int *c = (int*)malloc(sizeof(int)*(k+1));
memset(c, 0, (k+1)*sizeof(int));
//c[i] now contains the number of element equal to i;
for (i = 0; i < length; ++i)
c[a[i]] = c[a[i]] + 1;
//c[i] now contains the number of elements less than or equal to i;
for (j = 1; j <= k; ++j)
c[j] = c[j] + c[j - 1];
for (i = length - 1; i >= 0; i--)
{
b[c[a[i]] - 1] = a[i];
c[a[i]] = c[a[i]] - 1;
}//a[i]表示输入的元素,c[a[i]]表示出现的次数,那么b[c[a[i]] - 1]表示a[i]放到b数组中的位置
//放入之后,那么c[a[i]]的次数应该减少
}
int main()
{
int a[] = { 5, 6, 9, 5, 0, 8, 2, 1, 6, 9, 8, 3, 4, 8, 6, 7, 6, 3, 3, 3, 3, 3, 8, 8, 8,11 };
int len = sizeof(a) / sizeof(int);
cout << len << endl;
int b[26];
count_sort(a, b, 11, len);
for (int i = 0; i < len;i++)
cout << b[i] << " ";
}
原文地址:http://blog.csdn.net/chenxun_2010/article/details/41195721