Skip to content

Commit b794143

Browse files
authored
chore: Merge pull request TheAlgorithms#648 from mandy8055/countSortFix
Added the correct(stable) version of count sort. Changed function …
2 parents 05c3c3a + faed847 commit b794143

File tree

1 file changed

+19
-19
lines changed

1 file changed

+19
-19
lines changed

Sorts/CountingSort.js

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -8,31 +8,31 @@
88
* Animated Visual: https://www.cs.usfca.edu/~galles/visualization/CountingSort.html
99
*/
1010

11-
function countingSort (arr, min, max) {
12-
let i
13-
let z = 0
14-
const count = []
15-
16-
for (i = min; i <= max; i++) {
17-
count[i] = 0
11+
const countingSort = (arr, min, max) => {
12+
// Create an auxiliary resultant array
13+
const res = []
14+
// Create and initialize the frequency[count] array
15+
const count = new Array(max - min + 1).fill(0)
16+
// Populate the freq array
17+
for (let i = 0; i < arr.length; i++) {
18+
count[arr[i] - min]++
1819
}
19-
20-
for (i = 0; i < arr.length; i++) {
21-
count[arr[i]]++
20+
// Create a prefix sum array out of the frequency[count] array
21+
count[0] -= 1
22+
for (let i = 1; i < count.length; i++) {
23+
count[i] += count[i - 1]
2224
}
23-
24-
for (i = min; i <= max; i++) {
25-
while (count[i]-- > 0) {
26-
arr[z++] = i
27-
}
25+
// Populate the result array using the prefix sum array
26+
for (let i = arr.length - 1; i >= 0; i--) {
27+
res[count[arr[i] - min]] = arr[i]
28+
count[arr[i] - min]--
2829
}
29-
30-
return arr
30+
return res
3131
}
3232

3333
/**
34-
* Implementation of Counting Sort
35-
*/
34+
* Implementation of Counting Sort
35+
*/
3636
const array = [3, 0, 2, 5, 4, 1]
3737
// Before Sort
3838
console.log('\n- Before Sort | Implementation of Counting Sort -')

0 commit comments

Comments
 (0)