计数排序

计数排序的中间目标和快速排序的中间目标是一致的,都是需要找到一个元素在最终排好序的数组中的位置。快速排序使用了一种优雅的Partition技术,而计数排序如同它的名字描述的一样,进行计数得到最终位置。

 

试想一下如果知道一个元素前面的元素个数,那么也就是知道了该元素在最终数组中的位置了,为了得到元素之前的元素个数,对于计数排序做了如下限定:


待排序数组A的大小为n,而A中的元素的值在0-k之间,如果k = O(n)那么这种情况下比较时候使用计数排序。

使用一个C[1...k]的数组,用于统计1..k这k个值出现的次数,然后前后相加就可以得到小于等于某一个元素的元素个数了,这个时候需要稍微考虑一下如果存在数值相同的元素时算法是否依然有效。

 

下面参见测试代码:

 

View Code
/**
 * Algorithm Name: Counting Sort
 * @author: ivan jobs
 * @date: 2012.5.3
 * @email: ivan1377@163.com
 */

#include <cstdio>

/**
 * array A is the input array
 * array B is the output array with the same size n as array A
 * and elements in A, are between 0 to k exclusive.
 * array C with size of k is used to record something.
 */
void countingSort(int A[], int B[],int C[], int k, int n){
  int i;
  for(i=0;i<k;++i)
    C[i] = 0;
  for(i=0;i<n;++i)
    C[A[i]]++;    //counting numbers of elment A[i]
  for(i=1;i<k;++i)
    C[i] += C[i-1]; //calculate numbers of elments <= element A[i]

  
  for(i=n-1;i>=0;i--){
    B[C[A[i]]-1] = A[i];
    C[A[i]]--;
  }
}

int main(){
  int A[] = {3, 4, 2, 1, 8, 7, 6, 6, 5, 9};
  int B[10];
  int C[10];
  
  countingSort(A, B, C, 10, 10);
  
  int i;
  for(i=0;i<10;i++)
    printf("%d ", B[i]);
  printf("\n");
  return 0;
}

 

posted on 2012-05-03 11:43  涅槃火凤  阅读(198)  评论(0编辑  收藏  举报

导航