Thinking:
- Create the initial bucketSort function
- Create variables for i, min, max, and bucket size
- Find min and max value
- Create an amount of buckets
- Push values to correct buckets
- Sort buckets: it works by arranging elements into ‘buckets’ which are then sorted using another sort.
// bucket sort is most suitable for sorting an array of
// floating values or input is uniformly distributed over a range
let arr = [32, 6, 2, 3, 14, 15, 21, 25, 48, 45, 1, 39, 40, 61, 59, 60, 4, 34, 29, 7];
const selectionSort = (arr) => {
let temp, minIndex
for (let i = 0; i < arr.length - 1; i++) {
minIndex = i
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j
}
}
// until inner loop completed then exchange the value
temp = arr[minIndex]
arr[minIndex] = arr[i]
arr[i] = temp
}
return arr
}
const bucketSort = (arr, bucketsAmount) => {
let max = Math.max(...arr)
let min = Math.min(...arr)
// initializing each bucket
let eachBucket = Array.from({length: bucketsAmount}, () => [])
// decide the count of each bucket
let eachBucketLength = Math.floor((max - min) / bucketsAmount) + 1
// push values in a same range to the specific bucket
arr.forEach(currentValue => {
let i = Math.floor((currentValue - min) / eachBucketLength)
eachBucket[i].push(currentValue)
})
arr.length = 0
// A stable sort keeps the same relative order between any items with equal keys
eachBucket.forEach((subArray) => {
selectionSort(subArray)
subArray.forEach((element) => {
arr.push(element)
})
})
return arr
}
console.log(bucketSort(arr, 5))