设为首页 加入收藏

TOP

排序算法系列:计数排序
2013-01-13 11:00:04 来源: 作者: 【 】 浏览:438
Tags:排序 算法 系列 计数

  通俗理解:通过将待排序中的数组与辅助数组的下标建立一种联系,辅助数组储存与自己下标相等的原数组的每个元素的个数,然后进行一些操作保证计数排序的稳定性(可能理解的不够深刻,欢迎提出见解)。观看动态过程

  [cpp]

  int count_sort (int * const array, const int size)

  {

  int * count ;

  int * temp;

  int min, max ;

  int range, i ;

  min = max = array[0] ;

  for (i = 0; i < size; i++)

  {

  if (array[i] < min)

  min = array[i] ;

  else if (array[i] > max)

  max = array[i] ;

  }

  range = max - min + 1 ;

  count = (int *) malloc (sizeof (int) * range) ;

  if (NULL == count)

  return 0 ;

  temp = (int *) malloc (sizeof (int) * size) ;

  if (NULL == temp)

  {

  free (count) ;

  return 0 ;

  }

  for (i = 0; i < range; i++)

  count[i] = 0 ;

  for (i = 0; i < size; i++)

  count[array[i] - min]++;//记录与数组下标相等的数值的个数

  for (i = 1; i < range; i++)

  count[i] += count[i - 1];//储存自己数组下标数值在目标数组对应的位置,保证稳定性

  for (i = size - 1; i >= 0; i--)

  temp[--count[array[i] - min]] = array[i]; //将原数组按大小顺序储存到另一个数组

  for (i = 0; i < size; i++)

  array[i] = temp[i];

  free (count);

  free (temp);

  return 1;

  }

  运行时间是 Θ(n + k)

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇c语言二叉树--实现 下一篇排序算法系列:基数排序

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: