What is bucket sorting
Bucket sorting can be regarded as an upgrade method of counting sorting.
Bucket sorting refers to classifying a set of data according to a certain interval. It can be simply understood to look at the first digit to classify them.
Then sort in each bucket. At this time, you can use any sorting method.
Bucket sorting has restrictions on the data. If it is not the same number of digits, bucket sorting does not make much sense.
Algorithm process
- Classify data
- Sort within group
- combination
Algorithm implementation
function BucketSort(arr) {
let l = arr.length
if (l <= 1) return arr
let max = Math.max.apply(null, arr)
let result = []
let buckets = new Array(l).fill([])
for (let i = 0; i < l; i++) {
let BucketIndex = parseInt(arr[i].toString()[0])
buckets[BucketIndex].length == 0 ? buckets[BucketIndex] = [arr[i]] : buckets[BucketIndex].push(arr[i])
}
buckets.forEach(e => {
QuickSort(e, 0, e.length - 1)
result = result.concat(e)
})
return result
}
module.exports = BucketSort