Skip to content

Instantly share code, notes, and snippets.

@antoniopicone
Created October 21, 2017 17:07
Show Gist options
  • Save antoniopicone/d6dda54782e49bcb483b9f51f0e685e2 to your computer and use it in GitHub Desktop.
Save antoniopicone/d6dda54782e49bcb483b9f51f0e685e2 to your computer and use it in GitHub Desktop.
var CountingSort = function(A,k) {
var B=[];
B.push(null); // avoid undefined
var C=[];
for (var i=0;i<=k;i++){
C[i] = 0;
}
for(var j=1;j<A.length;j++) {
C[A[j]]++;
}
for(var i=1;i<=k;i++) {
C[i]=C[i]+C[i-1];
}
for(var j=A.length-1;j>0;j--) {
B[C[A[j]]] = A[j];
C[A[j]]--;
}
return B;
};
var arr = [null,7,3,1,4,9,5,2,8];
var k = Math.max.apply(this, arr);
console.log(CountingSort(arr,k));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment