Skip to content

Commit b362685

Browse files
committed
add javascript counting sort
1 parent fcffdac commit b362685

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

javascript/13_sorts/countingSort.js

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
const countingSort = array => {
2+
if (array.length <= 1) return
3+
4+
const max = findMaxValue(array)
5+
const counts = new Array(max + 1)
6+
7+
// 计算每个元素的个数,放入到counts桶中
8+
// counts下标是元素,值是元素个数
9+
array.forEach(element => {
10+
if (!counts[element]) {
11+
counts[element] = 0
12+
}
13+
counts[element]++
14+
})
15+
16+
// counts下标是元素,值是元素个数
17+
// 例如: array: [6, 4, 3, 1], counts: [empty, 1, empty, 1, 1, empty, 1]
18+
// i是元素, count是元素个数
19+
let sortedIndex = 0
20+
counts.forEach((count, i) => {
21+
while (count > 0) {
22+
array[sortedIndex] = i
23+
sortedIndex++
24+
count--
25+
}
26+
})
27+
// return array
28+
}
29+
30+
function findMaxValue(array) {
31+
let max = array[0]
32+
for (let i = 1; i < array.length; i++) {
33+
if (array[i] > max) {
34+
max = array[i]
35+
}
36+
}
37+
return max
38+
}

0 commit comments

Comments
 (0)