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

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
7
for (var i = 0; i < arrLen; i++) {
8
if (!bucket[arr[i]]) {
9
bucket[arr[i]] = 0;
10
}
11
bucket[arr[i]]++;
12
}
13
14
for (var j = 0; j < bucketLen; j++) {
15
while(bucket[j] > 0) {
16
arr[sortedIndex++] = j;
17
bucket[j]--;
18
}
19
}
20
21
return arr;
22
}
Copied!

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
Copied!

4. Go 代码实现

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

5. Java 代码实现

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

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
10
$arrLen = count($arr);
11
for ($i = 0; $i < $arrLen; $i++) {
12
if (!array_key_exists($arr[$i], $bucket)) {
13
$bucket[$arr[$i]] = 0;
14
}
15
$bucket[$arr[$i]]++;
16
}
17
18
$sortedIndex = 0;
19
foreach ($bucket as $key => $len) {
20
if($len !== null){
21
for($j = 0; $j < $len; $j++){
22
$arr[$sortedIndex++] = $key;
23
}
24
}
25
}
26
27
return $arr;
28
}
Copied!
Last modified 2yr ago