Skip to content

Instantly share code, notes, and snippets.

@CarlaTeo
Created July 11, 2022 02:33
Show Gist options
  • Save CarlaTeo/a92da1832627a9843e4ac957c8e86083 to your computer and use it in GitHub Desktop.
Save CarlaTeo/a92da1832627a9843e4ac957c8e86083 to your computer and use it in GitHub Desktop.
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