计数排序

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

template <class T>
void
countSort(T* array, int len)
{
  T max = array[0];
  T min = array[0];
  for(int i =0 ;i<len; ++i){
    if(array[i]>=max)
      max = array[i];
    if(array[i]<min)
      min = array[i];
  }
  T* countArray = (T*)calloc(max+1, sizeof(T));
  for(int i=0; i<len; ++i){
    countArray[array[i]]++;
  }
  int arrayIndex = 0;
  for(int i=0; i<(max+1); ++i){
    for(int j=0; j< countArray[i] && countArray[i]>0; ++j){
      array[arrayIndex++]=i;
    }
  }
  free(countArray);
}

int
main()
{
  int array[10] = {10, 2, 3, 40, 5, 6, 7, 8, 9, 10};
  const int arraylen = sizeof(array)/sizeof(int);
  countSort(array, arraylen);
  for(int i =0; i< arraylen; ++i){
    printf("%d ", array[i]);
  }
  printf("\n");
}
posted @ 2011-04-30 10:45  Richard Zhong  阅读(122)  评论(0编辑  收藏  举报