TypeScript Program to Implement Bucket Sort

TypeScript Program to Implement Bucket Sort

Bucket Sort is a simple and powerful sorting algorithm that works best when numbers are spread evenly across a known range. Instead of comparing elements again and again, Bucket Sort divides the data into smaller groups called buckets. Each bucket holds values that fall into a specific range, and then these buckets are sorted individually 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 much faster than traditional sorting methods when used in the right situation. Bucket Sort is commonly used for sorting floating-point numbers, percentages, marks, or values that are uniformly distributed. For beginners learning TypeScript, Bucket Sort is a great way to understand how data can be organized logically before sorting, making the overall process easier and more efficient.

Program 1: Basic Bucket Sort for Numbers Between 0 and 1

This program demonstrates the classic version of Bucket Sort, commonly taught for decimal numbers between 0 and 1. It is simple and perfect for understanding the core idea behind buckets.

function bucketSort(arr: number[]): number[] {

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

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

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

    let sortedArray: number[] = [];

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

    return sortedArray;

}

let values: number[] = [0.42, 0.32, 0.23, 0.52, 0.25, 0.47, 0.51];

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

This program places each number into a bucket based on its value and then sorts each bucket individually. Beginners can imagine placing numbers into boxes and then organizing each box before putting everything back together. This makes Bucket Sort easy to visualize and understand.

Program 2: Bucket Sort Using Fixed Bucket Size

This version uses a fixed number of buckets and works well when the range of values is known in advance.

function bucketSortFixed(arr: number[], bucketCount: number): number[] {

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

    for (let num of arr) {
        let index = Math.floor(((num - min) / (max - min + 1)) * bucketCount);
        buckets[index].push(num);
    }

    let result: number[] = [];

    for (let bucket of buckets) {
        bucket.sort((a, b) => a - b);
        result.push(...bucket);
    }

    return result;

}

let data: number[] = [29, 25, 3, 49, 9, 37, 21, 43];

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

This approach is useful when working with scores, ages, or any values within a known range. Beginners learn how bucket ranges affect sorting performance and how controlling bucket count can improve results.

Program 3: Bucket Sort Using While Loop Control

This program shows how Bucket Sort logic can still be applied while using different loop styles.

function bucketSortWhile(arr: number[]): number[] {

    let bucketSize = 5;
    let min = Math.min(...arr);
    let max = Math.max(...arr);

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

    let i = 0;

    while (i < arr.length) {

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

    }

    let sorted: number[] = [];
    let j = 0;

    while (j < buckets.length) {

        buckets[j].sort((a, b) => a - b);
        sorted.push(...buckets[j]);
        j++;

    }

    return sorted;

}

let numbers: number[] = [42, 32, 33, 52, 37, 47, 51];

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

This version helps beginners see that Bucket Sort is flexible and not tied to a single coding style. Understanding this makes it easier to adapt the algorithm in real projects.

Program 4: Bucket Sort Using Functional Style

This program uses a cleaner and more modern approach while keeping the logic beginner-friendly.

function bucketSortFunctional(arr: number[]): number[] {

    let bucketSize = 10;
    let min = Math.min(...arr);
    let max = Math.max(...arr);

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

    arr.forEach(num => {
        let index = Math.floor((num - min) / bucketSize);
        buckets[index].push(num);
    });

    return buckets.flatMap(bucket => bucket.sort((a, b) => a - b));

}

let valuesList: number[] = [88, 12, 45, 67, 23, 99, 34];

console.log("Sorted array:", bucketSortFunctional(valuesList));

This version is helpful for beginners learning modern TypeScript features. It shows that algorithms can be written in clean and readable ways without changing the core idea.

Program 5: Bucket Sort for Already Sorted Data

This program applies Bucket Sort to data that is already sorted to show stability and correctness.

function bucketSortFixed(arr: number[], bucketCount: number): number[] {

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

    for (let num of arr) {
        let index = Math.floor(((num - min) / (max - min + 1)) * bucketCount);
        buckets[index].push(num);
    }

    let result: number[] = [];

    for (let bucket of buckets) {
        bucket.sort((a, b) => a - b);
        result.push(...bucket);
    }

    return result;

}

let sortedData: number[] = [5, 10, 15, 20, 25];

console.log("Sorted array:", bucketSortFixed(sortedData, 3));

This example reassures beginners that Bucket Sort works correctly even when the input does not need sorting. It is important for algorithms to behave well in all scenarios.

Program 6: Bucket Sort with Duplicate Values

This program demonstrates how Bucket Sort handles duplicate numbers.

function bucketSortFixed(arr: number[], bucketCount: number): number[] {

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

    for (let num of arr) {
        let index = Math.floor(((num - min) / (max - min + 1)) * bucketCount);
        buckets[index].push(num);
    }

    let result: number[] = [];

    for (let bucket of buckets) {
        bucket.sort((a, b) => a - b);
        result.push(...bucket);
    }

    return result;

}

let duplicates: number[] = [4, 1, 3, 4, 2, 1, 5];

console.log("Sorted array:", bucketSortFixed(duplicates, 4));

Bucket Sort handles duplicates naturally, making it useful for real-world data where repeated values are common. Beginners can trust it for datasets like scores or ratings.

Program 7: Bucket Sort for Large Numbers

This program sorts larger integer values using bucket logic.

function bucketSortFixed(arr: number[], bucketCount: number): number[] {

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

    for (let num of arr) {
        let index = Math.floor(((num - min) / (max - min + 1)) * bucketCount);
        buckets[index].push(num);
    }

    let result: number[] = [];

    for (let bucket of buckets) {
        bucket.sort((a, b) => a - b);
        result.push(...bucket);
    }

    return result;

}

let largeNumbers: number[] = [102, 215, 87, 450, 320, 178];

console.log("Sorted array:", bucketSortFixed(largeNumbers, 6));

This example shows that Bucket Sort is not limited to small values. Beginners can apply it to many numeric datasets as long as the range is reasonable.

Program 8: Bucket Sort for Floating Point Numbers

This program focuses on decimal values, where Bucket Sort truly shines.

function bucketSort(arr: number[]): number[] {

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

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

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

    let sortedArray: number[] = [];

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

    return sortedArray;

}

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

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

This is one of the best use cases for Bucket Sort. Beginners can see why this algorithm is popular for sorting floating-point data.

Program 9: Bucket Sort Supporting Negative Numbers

By default, Bucket Sort may not handle negative numbers correctly. This program tweaks the logic to support them.

function bucketSortFixed(arr: number[], bucketCount: number): number[] {

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

    for (let num of arr) {
        let index = Math.floor(((num - min) / (max - min + 1)) * bucketCount);
        buckets[index].push(num);
    }

    let result: number[] = [];

    for (let bucket of buckets) {
        bucket.sort((a, b) => a - b);
        result.push(...bucket);
    }

    return result;

}

function bucketSortWithNegatives(arr: number[]): number[] {

    let negatives = arr.filter(n => n < 0).map(n => -n);
    let positives = arr.filter(n => n >= 0);

    negatives = bucketSortFixed(negatives, 5).reverse().map(n => -n);
    positives = bucketSortFixed(positives, 5);

    return negatives.concat(positives);

}

let mixedValues: number[] = [-12, 7, -3, 25, 0, -8, 15];

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

This version teaches beginners how algorithms can be extended to handle edge cases. It shows that limitations can often be solved with smart preprocessing.

Frequently Asked Questions (FAQ)

This section answers common beginner questions about Bucket Sort in TypeScript and helps clear confusion.

Q1. When should I use Bucket Sort instead of other sorting algorithms?
Bucket Sort is best when data is evenly distributed and falls within a known range.

Q2. Is Bucket Sort faster than Quick Sort?
In the right conditions, yes. However, it depends heavily on the input data.

Q3. Can Bucket Sort sort strings?
Bucket Sort is mainly designed for numeric data, though strings can be adapted with extra logic.

Q4. Is Bucket Sort stable?
It can be stable if the sorting method inside each bucket is stable.

Q5. Is Bucket Sort good for beginners?
Yes, it is very visual and helps beginners understand grouping and sorting concepts.

Conclusion

Bucket Sort is a friendly and efficient sorting algorithm when used in the right situations. In this article, we explored many TypeScript programs that implement Bucket Sort using different approaches, loop styles, and enhancements for negative and floating-point numbers. Each example showed how flexible and practical this algorithm can be.

If you are learning TypeScript or sorting algorithms, try running these programs and changing the data values. Practice will help you understand how buckets work and when to use this technique. Keep experimenting, stay curious, and enjoy your journey into algorithms and TypeScript programming.

Scroll to Top