Skip to content

Instantly share code, notes, and snippets.

@dandresfg
Created December 6, 2020 02:11
Show Gist options
  • Save dandresfg/c0a1bd19bcb5bb44bea96f21b4f6532a to your computer and use it in GitHub Desktop.
Save dandresfg/c0a1bd19bcb5bb44bea96f21b4f6532a to your computer and use it in GitHub Desktop.
This is my implementation of countingsort.
function countingSort(arr){
const aux = Array.from({length: Math.max(...arr)+1}, (v)=> 0)
for(let i = 0; i<arr.length; i++){
aux[arr[i]] = ++aux[arr[i]];
}
for (let i = 1; i < aux.length; i++) {
let prev = aux[i-1];
let next = prev + aux[i];
aux[i] = next;
}
const list = Array.from({length: aux[aux.length-1]})
for(let i = 0; i < list.length; i++){
const item = arr[i];
list[aux[item]-1] = item;
aux[item] = --aux[item];
}
return list;
}
countingSort([4,9,2,4,7,6,11]);
// (7) [ 2, 4, 4, 6, 7, 9, 11 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment