计数排序

计数排序的核心在于将输入的数据值转化为键存储在额外开辟的数组空间中。作为一种线性时间复杂度的排序,计数排序要求输入的数据必须是有确定范围的整数。

1. 动图演示

动图演示

2. JavaScript 代码实现

  1. function countingSort(arr, maxValue) {
  2. var bucket = new Array(maxValue+1),
  3. sortedIndex = 0;
  4. arrLen = arr.length,
  5. bucketLen = maxValue + 1;
  6. for (var i = 0; i < arrLen; i++) {
  7. if (!bucket[arr[i]]) {
  8. bucket[arr[i]] = 0;
  9. }
  10. bucket[arr[i]]++;
  11. }
  12. for (var j = 0; j < bucketLen; j++) {
  13. while(bucket[j] > 0) {
  14. arr[sortedIndex++] = j;
  15. bucket[j]--;
  16. }
  17. }
  18. return arr;
  19. }

3. Python 代码实现

  1. def countingSort(arr, maxValue):
  2. bucketLen = maxValue+1
  3. bucket = [0]*bucketLen
  4. sortedIndex =0
  5. arrLen = len(arr)
  6. for i in range(arrLen):
  7. if not bucket[arr[i]]:
  8. bucket[arr[i]]=0
  9. bucket[arr[i]]+=1
  10. for j in range(bucketLen):
  11. while bucket[j]>0:
  12. arr[sortedIndex] = j
  13. sortedIndex+=1
  14. bucket[j]-=1
  15. return arr

4. Go 代码实现

  1. func countingSort(arr []int, maxValue int) []int {
  2. bucketLen := maxValue + 1
  3. bucket := make([]int, bucketLen) // 初始为0的数组
  4. sortedIndex := 0
  5. length := len(arr)
  6. for i := 0; i < length; i++ {
  7. bucket[arr[i]] += 1
  8. }
  9. for j := 0; j < bucketLen; j++ {
  10. for bucket[j] > 0 {
  11. arr[sortedIndex] = j
  12. sortedIndex += 1
  13. bucket[j] -= 1
  14. }
  15. }
  16. return arr
  17. }

5. Java 代码实现

  1. public class CountingSort implements IArraySort {
  2. @Override
  3. public int[] sort(int[] sourceArray) throws Exception {
  4. // 对 arr 进行拷贝,不改变参数内容
  5. int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);
  6. int maxValue = getMaxValue(arr);
  7. return countingSort(arr, maxValue);
  8. }
  9. private int[] countingSort(int[] arr, int maxValue) {
  10. int bucketLen = maxValue + 1;
  11. int[] bucket = new int[bucketLen];
  12. for (int value : arr) {
  13. bucket[value]++;
  14. }
  15. int sortedIndex = 0;
  16. for (int j = 0; j < bucketLen; j++) {
  17. while (bucket[j] > 0) {
  18. arr[sortedIndex++] = j;
  19. bucket[j]--;
  20. }
  21. }
  22. return arr;
  23. }
  24. private int getMaxValue(int[] arr) {
  25. int maxValue = arr[0];
  26. for (int value : arr) {
  27. if (maxValue < value) {
  28. maxValue = value;
  29. }
  30. }
  31. return maxValue;
  32. }
  33. }

6. PHP 代码实现

  1. function countingSort($arr, $maxValue = null)
  2. {
  3. if ($maxValue === null) {
  4. $maxValue = max($arr);
  5. }
  6. for ($m = 0; $m < $maxValue + 1; $m++) {
  7. $bucket[] = null;
  8. }
  9. $arrLen = count($arr);
  10. for ($i = 0; $i < $arrLen; $i++) {
  11. if (!array_key_exists($arr[$i], $bucket)) {
  12. $bucket[$arr[$i]] = 0;
  13. }
  14. $bucket[$arr[$i]]++;
  15. }
  16. $sortedIndex = 0;
  17. foreach ($bucket as $key => $len) {
  18. if ($len !== null) $arr[$sortedIndex++] = $key;
  19. }
  20. return $arr;
  21. }