Skip to content

Commit 376f60d

Browse files
committed
Added the correct and stable version of count sort. Changed function declaration to ES6 style.
1 parent 05c3c3a commit 376f60d

File tree

1 file changed

+22
-15
lines changed

1 file changed

+22
-15
lines changed

Sorts/CountingSort.js

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,31 +8,38 @@
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
11+
const countingSort = (arr, min, max) => {
12+
// Create an auxiliary resultant array
13+
const res = []
14+
// Create the freq array
1415
const count = []
16+
let len = max - min + 1
1517

16-
for (i = min; i <= max; i++) {
18+
for (let i = 0; i < len; i++) {
1719
count[i] = 0
1820
}
19-
20-
for (i = 0; i < arr.length; i++) {
21-
count[arr[i]]++
21+
// Populate the freq array
22+
for (let i = 0; i < arr.length; i++) {
23+
count[arr[i] - min] += 1
2224
}
23-
24-
for (i = min; i <= max; i++) {
25-
while (count[i]-- > 0) {
26-
arr[z++] = i
27-
}
25+
// Create a prefix sum array out of the freq array
26+
count[0] -= 1
27+
for (let i = 1; i < count.length; i++) {
28+
count[i] += count[i - 1]
2829
}
29-
30+
// Populate the result array using the prefix sum array
31+
for (let i = arr.length - 1; i >= 0; i--) {
32+
res[count[arr[i] - min]] = arr[i]
33+
count[arr[i] - min]--
34+
}
35+
// Copy the result back to back to original array
36+
arr = [...res]
3037
return arr
3138
}
3239

3340
/**
34-
* Implementation of Counting Sort
35-
*/
41+
* Implementation of Counting Sort
42+
*/
3643
const array = [3, 0, 2, 5, 4, 1]
3744
// Before Sort
3845
console.log('\n- Before Sort | Implementation of Counting Sort -')

0 commit comments

Comments
 (0)