Created
July 11, 2022 02:33
-
-
Save CarlaTeo/a92da1832627a9843e4ac957c8e86083 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function countSort(array) { | |
const counts = {}; | |
for(const num of array) { | |
if(counts[num]) counts[num] += 1; | |
else counts[num] = 1; | |
} | |
for(let idx = 0; idx < Object.keys(counts).length - 1; idx++) { | |
counts[Object.keys(counts)[idx + 1]] += counts[Object.keys(counts)[idx]]; | |
} | |
const result = []; | |
for(const num of array.reverse()) { | |
result[counts[num] - 1] = num; | |
counts[num] -= 1; | |
} | |
return result; | |
} | |
console.log(countSort([7,3,6,5,1])) // [1,3,5,6,7] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment