"Introduction to Algorithms" ʚReading Notes & Analysis ɞ Chapter 8-Bucket Sorting (including js version code implementation)

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

  1. Classify data
  2. Sort within group
  3. 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

Guess you like

Origin blog.csdn.net/weixin_38616850/article/details/110926381