Skip to content

Instantly share code, notes, and snippets.

@vaidehijoshi
Last active July 17, 2017 01:55
Show Gist options
  • Save vaidehijoshi/17ace27875914876c31474396c841813 to your computer and use it in GitHub Desktop.
Save vaidehijoshi/17ace27875914876c31474396c841813 to your computer and use it in GitHub Desktop.
// Notice that we needed to know the max/min value in order to use counting sort at all!
function countingSort(array, minimumValue, maximumValue) {
var i;
var z = 0;
var count = [];
// Count the instances of each element.
for (i = minimumValue; i <= maximumValue; i++) {
count[i] = 0;
}
// We now have a placeholder array that we'll use to keep
// track of which element will be sorted into each index.
console.log(count);
// Build up our index count array.
for (i=0; i < array.length; i++) {
count[array[i]]++;
}
console.log(count);
// Modify array and move elements into their sorted location.
for (i = minimumValue; i <= maximumValue; i++) {
while (count[i]-- > 0) {
console.log('item at index ' + z + ' is: ', array[z]);
array[z++] = i;
console.log('moving item ' + i + ' to correct location');
}
}
console.log("Hooray! Array is now sorted!");
return array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment