Skip to content

Instantly share code, notes, and snippets.

@CarlaTeo
Created May 16, 2021 20:29
Show Gist options
  • Save CarlaTeo/c3e126c71399371a1c49d861c05d8135 to your computer and use it in GitHub Desktop.
Save CarlaTeo/c3e126c71399371a1c49d861c05d8135 to your computer and use it in GitHub Desktop.
[JS] Bucket sort
// Bucket Sort: O(N) method to sort natural numbers
function bucketSort(array) {
const buckets = [];
array.forEach(number => {
if(!buckets[number]) buckets[number] = 1;
else buckets[number] += 1;
})
const sortedArray = [];
buckets.forEach((counter, number) => {
for(let amount = 1; amount <= counter; amount++) {
sortedArray.push(number);
}
});
return sortedArray;
}
// ---------------------------------------- Test -------------------------------------------//
const array = [8, 7, 1, 6, 9, 4, 8];
console.log(bucketSort(array)); // [ 1, 4, 6, 7, 8, 8, 9]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment