算法导论学习笔记(一)排序算法之计数排序

来源:互联网 发布:如何编写抢购软件 编辑:程序博客网 时间:2024/05/20 19:19

基本思想

对于一个数x,确定小于x的元素个数。

即找到n个比x小的数,那么x在数列中为第n+1小的数,则确定其排序位置。

算导上的伪代码

COUNTING-SORT(A,B,k)1   let C[0...k] be a new array2   for i = 0 to k3       C[i] = 04   for j = 1 to A.length5       C[A[j]] = C[A[j]] + 16   //C[i] now contains the number of elements equal to i.7   for i = 1 to k8       C[i] = C[i] + C[i-1]9   //C[i] now contains the number of elements less than or equal to i.10  for j = A.length downto 111      B[C[A[j]]] = A[j]12      C[A[j]] = C[A[j]] - 1

执行时间

第3行和第7行各执行k次,即O(k);
第5行和第11、12行各执行n次,即O(n);
总执行时间为O(n+k);
当k = O(n)时,执行时间为O(n)。

程序代码

void countSort(int *sortArray,int n,int k,int *b){    int c[k+10];    for(int i=0;i<k;i++){        c[i] = 0;    }    for(int i=0;i<n;i++){        c[sortArray[i]]++;    }    for(int i=1;i<k;i++){        c[i] += c[i-1];    }    for(int i=n-1;i>=0;i--){        b[c[sortArray[i]]-1] = sortArray[i];        c[sortArray[i]]--;    }}
0 0