前面介绍的几种排序算法,都是基于不同位置的元素比较,算法平均时间复杂度理论最好值是θ(nlgn).

今天介绍一种新的排序算法,计数排序(Counting sort),计数排序是一个非基于比较的线性时间排序算法。它对输入的数据有附加的限制条件:输入序列中数据取值范围有限,比如都是小于upperLimit的整数;

算法分3步实现:

1)遍历输入序列,统计不同取值的个数,放入计数数组;

2)遍历计数数组,计算不大于各个取值的个数,更新计数数组;

3)逆序遍历输入序列,结合计数数组中个数,将数据放到输出数组中。

(一)算法实现

 

 1 protected void sort(int[] toSort) {
 2         int[] result = new int[toSort.length];
 3         int[] countingArray = new int[upperLimit];
 4         for (int i = 0; i < toSort.length; i++) {
 5             countingArray[toSort[i]]++;
 6         }
 7         for (int i = 1; i < countingArray.length; i++) {
 8             countingArray[i] += countingArray[i - 1];
 9         }
10 
11         for (int i = toSort.length - 1; i >= 0; i--) {
12             result[countingArray[toSort[i]] - 1] = toSort[i];
13             countingArray[toSort[i]]--;
14         }
15 
16         System.arraycopy(result, 0, toSort, 0, result.length);
17     }
Counting Sort

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-27
  • 2021-08-11
  • 2022-12-23
  • 2022-02-10
猜你喜欢
  • 2021-08-06
  • 2021-09-06
  • 2022-01-18
  • 2022-01-01
  • 2021-12-10
  • 2021-11-17
相关资源
相似解决方案