JavaScript Program to Implement Bucket Sort

JavaScript Program to Implement Bucket Sort

Bucket Sort is a simple and clever sorting algorithm that works best when numbers are spread evenly over a known range. Instead of comparing every value with every other value, Bucket Sort places numbers into small groups called buckets. Each bucket holds values that fall within a specific range, and once the buckets are filled, the values inside each bucket are sorted and combined to produce the final sorted result.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

This algorithm matters because it can be very fast in the right situations. Bucket Sort is often used when dealing with floating-point numbers, scores, percentages, or any data that is evenly distributed. For beginners, learning Bucket Sort is helpful because it introduces a new way of thinking about sorting. Instead of focusing only on comparisons, it shows how organizing data first can make sorting easier and faster in JavaScript.

Program 1: Basic Bucket Sort using loops

This program demonstrates a simple Bucket Sort implementation in JavaScript using loops. It works well for numbers between 0 and 1.

function bucketSort(arr, bucketSize = 5) {

    if (arr.length === 0) return arr;

    let minValue = Math.min(...arr);
    let maxValue = Math.max(...arr);

    let bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1;
    let buckets = Array.from({ length: bucketCount }, () => []);

    for (let i = 0; i < arr.length; i++) {

        let index = Math.floor((arr[i] - minValue) / bucketSize);
        buckets[index].push(arr[i]);

    }

    let sortedArray = [];

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

        buckets[i].sort((a, b) => a - b);
        sortedArray = sortedArray.concat(buckets[i]);

    }

    return sortedArray;

}

let numbers = [0.42, 0.32, 0.23, 0.52, 0.25, 0.47, 0.51];

console.log("Sorted array:", bucketSort(numbers));

This program first finds the minimum and maximum values to decide how many buckets are needed. Each number is placed into a bucket based on its value, and each bucket is sorted individually. Beginners can understand this as first grouping similar values together and then sorting each small group, which makes the process feel simple and logical.

Program 2: Bucket Sort with clear range handling

This version focuses on clarity by clearly calculating bucket ranges. It is easier for beginners to follow step by step.

function bucketSortClear(arr, bucketCount = 5) {

    let min = Math.min(...arr);
    let max = Math.max(...arr);
    let buckets = Array.from({ length: bucketCount }, () => []);

    for (let i = 0; i < arr.length; i++) {

        let index = Math.floor(((arr[i] - min) / (max - min + 1)) * bucketCount);
        buckets[index].push(arr[i]);

    }

    let result = [];

    for (let i = 0; i < buckets.length; i++) {
        buckets[i].sort((a, b) => a - b);
        result = result.concat(buckets[i]);
    }

    return result;

}

let values = [29, 25, 3, 49, 9, 37, 21, 43];

console.log("Sorted array:", bucketSortClear(values));

Here, the bucket index is calculated using a clear mathematical formula. This helps beginners see how values are distributed evenly across buckets. It is useful because it works well when the data range is known and fairly balanced.

Program 3: Bucket Sort using insertion sort inside buckets

This program replaces the built-in sort with Insertion Sort inside each bucket. It helps beginners combine two algorithms together.

function insertionSort(arr) {

    for (let i = 1; i < arr.length; i++) {

        let key = arr[i];
        let j = i - 1;

        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j--;
        }

        arr[j + 1] = key;

    }

    return arr;

}

function bucketSortWithInsertion(arr, bucketSize = 5) {

    let min = Math.min(...arr);
    let max = Math.max(...arr);
    let bucketCount = Math.floor((max - min) / bucketSize) + 1;
    let buckets = Array.from({ length: bucketCount }, () => []);

    for (let i = 0; i < arr.length; i++) {
        let index = Math.floor((arr[i] - min) / bucketSize);
        buckets[index].push(arr[i]);
    }

    let sorted = [];

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

    return sorted;

}

let data = [42, 32, 33, 52, 37, 47, 51];

console.log("Sorted array:", bucketSortWithInsertion(data));

This program shows how Bucket Sort often relies on another sorting method for each bucket. Insertion Sort is a good choice because buckets are usually small. Beginners benefit from this example because it shows how algorithms can work together instead of alone.

Program 4: Bucket Sort for decimal numbers

This example focuses on sorting decimal values, which is one of the most common real-world uses of Bucket Sort.

function bucketSortDecimals(arr) {

    let buckets = Array.from({ length: 10 }, () => []);

    for (let i = 0; i < arr.length; i++) {
        let index = Math.floor(arr[i] * 10);
        buckets[index].push(arr[i]);
    }

    let result = [];

    for (let i = 0; i < buckets.length; i++) {
        buckets[i].sort((a, b) => a - b);
        result = result.concat(buckets[i]);
    }

    return result;

}

let decimals = [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21];

console.log("Sorted array:", bucketSortDecimals(decimals));

This program assumes values are between 0 and 1 and uses that fact to place numbers into buckets. Beginners can clearly see how decimals naturally fit into bucket ranges. It is very useful for percentages, probabilities, and scores.

Program 5: Bucket Sort as a reusable utility function

This version focuses on clean and reusable code that can be used in different JavaScript programs.

function bucketSortUtility(arr, bucketSize = 5) {

    if (arr.length === 0) return arr;

    let min = Math.min(...arr);
    let max = Math.max(...arr);
    let bucketCount = Math.floor((max - min) / bucketSize) + 1;
    let buckets = Array.from({ length: bucketCount }, () => []);

    for (let i = 0; i < arr.length; i++) {

        let index = Math.floor((arr[i] - min) / bucketSize);
        buckets[index].push(arr[i]);

    }

    return buckets.reduce((result, bucket) => {

        bucket.sort((a, b) => a - b);
        return result.concat(bucket);

    }, []);

}

let items = [15, 3, 27, 9, 21, 6, 18];

console.log("Sorted array:", bucketSortUtility(items));

This program returns the sorted array directly, making it easy to reuse in other projects. Beginners will find this helpful because it feels like real-world JavaScript code. It also encourages writing clean and maintainable functions.

Program 6: Bucket Sort that handles negative numbers

This program extends the standard Bucket Sort to handle arrays that include negative numbers. It works by separating negative and positive numbers into different sets of buckets, sorting each set individually, and then combining them back together.

function bucketSortWithNegatives(arr, bucketSize = 5) {

    if (arr.length === 0) return arr;

    let negatives = arr.filter(num => num < 0).map(num => Math.abs(num));
    let positives = arr.filter(num => num >= 0);

    function bucketSortBasic(nums) {

        if (nums.length === 0) return nums;

        let min = Math.min(...nums);
        let max = Math.max(...nums);
        let bucketCount = Math.floor((max - min) / bucketSize) + 1;
        let buckets = Array.from({ length: bucketCount }, () => []);

        for (let i = 0; i < nums.length; i++) {

            let index = Math.floor((nums[i] - min) / bucketSize);
            buckets[index].push(nums[i]);

        }

        return buckets.reduce((sorted, bucket) => {

            bucket.sort((a, b) => a - b);
            return sorted.concat(bucket);

        }, []);

    }

    let sortedPositives = bucketSortBasic(positives);
    let sortedNegatives = bucketSortBasic(negatives)
        .reverse()
        .map(num => -num);

    return sortedNegatives.concat(sortedPositives);

}

let numbers = [15, -3, 27, -9, 21, -6, 18];

console.log("Sorted array:", bucketSortWithNegatives(numbers));

In this program, negative numbers are converted to positive numbers so they can be placed into buckets normally. After sorting, they are reversed and converted back to negative values to maintain proper order. Beginners can think of it as sorting two separate groups and then merging them. This approach keeps the logic simple while extending Bucket Sort to handle negative numbers in real-world datasets.

Frequently Asked Questions (FAQ)

This section answers common beginner questions about Bucket Sort in JavaScript in a simple and friendly way.

Q1. What is Bucket Sort in JavaScript?
Bucket Sort is a sorting algorithm that groups values into buckets and sorts each bucket separately before combining them.

Q2. When should Bucket Sort be used?
Bucket Sort works best when data is evenly distributed over a known range, such as percentages or decimal values.

Q3. Is Bucket Sort faster than Quick Sort?
Bucket Sort can be faster in specific cases, but Quick Sort is more flexible and works well for general data.

Q4. Does Bucket Sort work with negative numbers?
Bucket Sort can work with negative numbers if the bucket range is handled properly.

Q5. Should beginners learn Bucket Sort?
Yes, Bucket Sort is great for beginners because it introduces a different way of thinking about sorting.

Conclusion

Bucket Sort is a practical and interesting sorting algorithm that shows how organizing data first can make sorting easier. It works especially well with evenly distributed values and decimals, making it useful in many real-world situations. Learning Bucket Sort in JavaScript also helps beginners understand how multiple algorithms can work together.

The best way to learn Bucket Sort is to practice it with different data sets. Try changing bucket sizes, sorting decimals, or combining it with other sorting methods. With regular practice, Bucket Sort will become a valuable part of your JavaScript algorithm knowledge.

Scroll to Top