Bucket

Bucket sort is a sorting algorithm that works by distributing the elements of an array into a number of buckets.

Each bucket is then sorted individually, either using a different sorting algorithm or by recursively applying the bucket sort algorithm.

pseudocode:

function bucketSort(array, bucketSize)
    create empty buckets
    for i = 0 to length(array) - 1
        insert array[i] into appropriate bucket
    for each bucket
        sort elements in the bucket (using another sorting algorithm)
    concatenate all buckets to form the sorted array
const numbers = [99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0];

function BucketSort(array, bucketSize) {
    if (array.length === 0) {
        return array;
    }

    let minValue = array[0];
    let maxValue = array[0];
    for (let i = 1; i < array.length; i++) {
        if (array[i] < minValue) {
            minValue = array[i];
        } else if (array[i] > maxValue) {
            maxValue = array[i];
        }
    }

    const bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1;
    const buckets = new Array(bucketCount);

    for (let i = 0; i < buckets.length; i++) {
        buckets[i] = [];
    }

    for (let i = 0; i < array.length; i++) {
        const bucketIndex = Math.floor((array[i] - minValue) / bucketSize);
        buckets[bucketIndex].push(array[i]);
    }

    const sortedArray = [];
    for (let i = 0; i < buckets.length; i++) {
        if (buckets[i].length > 0) {
            buckets[i].sort((a, b) => a - b);
            sortedArray.push(...buckets[i]);
        }
    }

    return sortedArray;
}

console.log(BucketSort(numbers, 10));

In this implementation:

  • We first find the minimum and maximum values in the array to determine the range of values.

  • Based on the range, we create buckets and distribute elements into these buckets.

  • We then sort each bucket individually. Here, we're using insertion sort, but you can use any sorting algorithm you prefer.

  • Finally, we concatenate the sorted buckets to get the fully sorted array.

Keep in mind that the performance of bucket sort depends on the distribution of the elements in the input array.

It's most efficient when the elements are uniformly distributed across the range.

Last updated