Skip to content

Instantly share code, notes, and snippets.

@ungarson
Last active April 6, 2019 06:59
Show Gist options
  • Save ungarson/69e0cf17f6725d5cee7271b50e98fbdf to your computer and use it in GitHub Desktop.
Save ungarson/69e0cf17f6725d5cee7271b50e98fbdf to your computer and use it in GitHub Desktop.
Bucket sort in javascript
let insertionSort = (inputArr) => {
let length = inputArr.length;
for (let i = 1; i < length; i++) {
let key = inputArr[i];
let j = i - 1;
while (j >= 0 && inputArr[j] > key) {
inputArr[j + 1] = inputArr[j];
j = j - 1;
}
inputArr[j + 1] = key;
}
return inputArr;
};
function bucketSort(arr) {
let objectOfArrays = {
0: [],
1: [],
2: [],
3: [],
4: [],
5: [],
6: [],
7: [],
8: [],
9: []
}
for (let i = 0; i < arr.length; i++) {
let intPart = (arr[i] * 10) | 0;
objectOfArrays[intPart].push(arr[i]);
}
let sortedArray = [];
for (let i = 0; i < 9; i++) {
sortedArray = sortedArray.concat(insertionSort(objectOfArrays[i]));
}
return sortedArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment