|
8 | 8 | * Animated Visual: https://www.cs.usfca.edu/~galles/visualization/CountingSort.html |
9 | 9 | */ |
10 | 10 |
|
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 |
14 | 15 | const count = [] |
| 16 | + let len = max - min + 1 |
15 | 17 |
|
16 | | - for (i = min; i <= max; i++) { |
| 18 | + for (let i = 0; i < len; i++) { |
17 | 19 | count[i] = 0 |
18 | 20 | } |
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 |
22 | 24 | } |
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] |
28 | 29 | } |
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] |
30 | 37 | return arr |
31 | 38 | } |
32 | 39 |
|
33 | 40 | /** |
34 | | -* Implementation of Counting Sort |
35 | | -*/ |
| 41 | + * Implementation of Counting Sort |
| 42 | + */ |
36 | 43 | const array = [3, 0, 2, 5, 4, 1] |
37 | 44 | // Before Sort |
38 | 45 | console.log('\n- Before Sort | Implementation of Counting Sort -') |
|
0 commit comments