C数据结构—计数排序实现
计数排序是一个非基于比较的排序算法,该算法于1954年由 Harold H. Seward 提出。它的优势在于在对一定范围内的整数排序时,它的复杂度为Ο(n+k)(其中k是整数的范围),快于任何比较排序算法。[1-2] 当然这是一种牺牲空间换取时间的做法,而且当O(k)>O(n*log(n))的时候其效率反而不如基于比较的排序(基于比较的排序的时间复杂度在理论上的下限是O(n*log(n)), 如归并排序,堆排序)
算法思想
计数排序对输入的数据有附加的限制条件:
1、输入的线性表的元素属于有限偏序集S;
2、设输入的线性表的长度为n,|S|=k(表示集合S中元素的总数目为k),则k=O(n)。
在这两个条件下,计数排序的复杂性为O(n)。
计数排序的基本思想是对于给定的输入序列中的每一个元素x,确定该序列中值小于x的元素的个数(此处并非比较各元素的大小,而是通过对元素值的计数和计数值的累加来确定)。一旦有了这个信息,就可以将x直接存放到最终的输出序列的正确位置上。例如,如果输入序列中只有17个元素的值小于x的值,则x可以直接存放在输出序列的第18个位置上。当然,如果有多个元素具有相同的值时,我们不能将这些元素放在输出序列的同一个位置上,因此,上述方案还要作适当的修改。
算法过程
假设输入的线性表L的长度为n,L=L1,L2,..,Ln;线性表的元素属于有限偏序集S,|S|=k且k=O(n),S={S1,S2,..Sk};则计数排序可以描述如下:
1、扫描整个集合S,对每一个Si∈S,找到在线性表L中小于等于Si的元素的个数T(Si);
2、扫描整个线性表L,对L中的每一个元素Li,将Li放在输出线性表的第T(Li)个位置上,并将T(Li)减1。
算法实现
/* Count Sort
Input: int arrayA - An array that contains the data to be sorted.
int k - An integer representing the largest input value.
Output: int* - The function returns a pointer to the original array
with the sorted output.
Compiled With: g++ for i686-apple-darwin10
gcc version 4.2.1 (Apple Inc. build 5666)
*/
int *FregmentArrange::countSort(int arrayA[], int k) {
int arrayA_length = sizeof(arrayA);
int * arrayB = (int *)malloc(arrayA_length * sizeof(int));
int * arrayC = (int *)malloc((k+1) * sizeof(int));
for(int i = 0; i <= k; i++)
arrayC[i] = 0;
//Count the number of each number (confusing I know) and place that
//value into the array C.
for(int j = 0; j < arrayA_length; j++)
arrayC[arrayA[j]] = arrayC[arrayA[j]] + 1;
//Place the number of elements less than each value at i into array C.
for(int i = 1; i <= k; i++)
arrayC[i] = arrayC[i] + arrayC[i-1];
//Place each element of arrayA into its correct sorted position in the
//output array B.
for(int j = arrayA_length - 1; j >= 0; j--) {
arrayB[arrayC[arrayA[j]] - 1] = arrayA[j];
arrayC[arrayA[j]] = arrayC[arrayA[j]] - 1;
}
//Overwrite the original arrayA with the output arrayB.
for(int i = 0; i < sizeof(arrayA); i++)
arrayA[i] = arrayB[i];
//Release any used memory. You want to do this because you don't want
//multiple calls to the sort to use an increasingly large amount of
//memory.
free(arrayB);
free(arrayC);
//Return a pointer to the output arrayB.
return arrayA;
}