Created
May 16, 2021 20:29
-
-
Save CarlaTeo/c3e126c71399371a1c49d861c05d8135 to your computer and use it in GitHub Desktop.
[JS] Bucket sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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