chore: Merge pull request #648 from mandy8055/countSortFix

Added the correct(stable) version of count sort. Changed function …
This commit is contained in:
Rak Laptudirm
2021-08-08 17:59:30 +05:30
committed by GitHub

View File

@ -8,26 +8,26 @@
* Animated Visual: https://www.cs.usfca.edu/~galles/visualization/CountingSort.html * Animated Visual: https://www.cs.usfca.edu/~galles/visualization/CountingSort.html
*/ */
function countingSort (arr, min, max) { const countingSort = (arr, min, max) => {
let i // Create an auxiliary resultant array
let z = 0 const res = []
const count = [] // Create and initialize the frequency[count] array
const count = new Array(max - min + 1).fill(0)
for (i = min; i <= max; i++) { // Populate the freq array
count[i] = 0 for (let i = 0; i < arr.length; i++) {
count[arr[i] - min]++
} }
// Create a prefix sum array out of the frequency[count] array
for (i = 0; i < arr.length; i++) { count[0] -= 1
count[arr[i]]++ for (let i = 1; i < count.length; i++) {
count[i] += count[i - 1]
} }
// Populate the result array using the prefix sum array
for (i = min; i <= max; i++) { for (let i = arr.length - 1; i >= 0; i--) {
while (count[i]-- > 0) { res[count[arr[i] - min]] = arr[i]
arr[z++] = i count[arr[i] - min]--
} }
} return res
return arr
} }
/** /**