JavaScript Program to Implement Radix Sort

JavaScript Program to Implement Radix Sort

Radix Sort is a special kind of sorting algorithm that works very differently from the comparison-based sorts like Bubble Sort or Quick Sort. Instead of comparing numbers directly with each other, Radix Sort looks at individual digits of the numbers. It starts from one digit position, usually the rightmost digit, and sorts the numbers step by step until the entire list becomes sorted. Because of this approach, Radix Sort can be very fast when working with numbers that have a fixed number of digits.

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

Radix Sort matters because it shows beginners that not all sorting algorithms work the same way. In real-world systems such as digital clocks, phone numbers, IDs, and large numeric datasets, Radix Sort can be extremely efficient. Learning how to implement Radix Sort in JavaScript helps beginners understand non-comparison sorting and builds a deeper appreciation of how algorithms can be designed in creative ways.

Program 1: Basic Radix Sort using loops

This program shows the most common way to implement Radix Sort in JavaScript using loops. It sorts numbers by processing each digit from right to left.

function radixSort(arr) {

    const maxNum = Math.max(...arr);
    let digitPlace = 1;

    while (Math.floor(maxNum / digitPlace) > 0) {

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

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

            let digit = Math.floor(arr[i] / digitPlace) % 10;
            buckets[digit].push(arr[i]);

        }

        arr = [].concat(...buckets);
        digitPlace *= 10;

    }

    return arr;

}

let numbers = [170, 45, 75, 90, 802, 24, 2, 66];

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

This program finds the largest number to know how many digits it needs to process. It then groups numbers into buckets based on the current digit and combines them back into an array. Beginners can understand this by thinking of sorting numbers one digit at a time, just like organizing cards by their numbers.

Program 2: Radix Sort with clear digit extraction

This version focuses on clarity by using helper logic to extract digits. It helps beginners clearly see how each digit is handled.

function getDigit(num, place) {
    return Math.floor(num / place) % 10;
}

function radixSortClear(arr) {

    let max = Math.max(...arr);
    let place = 1;

    while (Math.floor(max / place) > 0) {

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

        for (let i = 0; i < arr.length; i++) {
            let digit = getDigit(arr[i], place);
            buckets[digit].push(arr[i]);
        }

        arr = [].concat(...buckets);
        place *= 10;

    }

    return arr;

}

let values = [121, 432, 564, 23, 1, 45, 788];

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

Here, the digit extraction logic is separated to make the code easier to read. This is useful for beginners because it breaks the problem into smaller, understandable parts. It also shows how helper functions improve code clarity.

Program 3: Radix Sort using a reusable function style

This program wraps Radix Sort into a reusable function that can be applied to different arrays. It is closer to real-world JavaScript usage.

function radixSortReusable(arr) {

    let maxDigits = Math.max(...arr).toString().length;

    for (let i = 0; i < maxDigits; i++) {

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

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

            let digit = Math.floor(arr[j] / Math.pow(10, i)) % 10;
            buckets[digit].push(arr[j]);

        }

        arr = [].concat(...buckets);

    }

    return arr;

}

let data = [93, 45, 12, 7, 304, 89];

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

This program calculates the number of digits first and then sorts the array digit by digit. Beginners will find this approach helpful because it clearly limits how many passes the algorithm makes. It also shows how math functions are useful in sorting.

Program 4: Radix Sort handling numbers with different lengths

This example demonstrates how Radix Sort handles numbers with different digit lengths naturally. No extra comparison logic is required.

function radixSortDifferentLengths(arr) {

    let maxNum = Math.max(...arr);
    let exp = 1;

    while (Math.floor(maxNum / exp) > 0) {

        let output = new Array(arr.length).fill(0);
        let count = new Array(10).fill(0);

        for (let i = 0; i < arr.length; i++) {
            let index = Math.floor(arr[i] / exp) % 10;
            count[index]++;
        }

        for (let i = 1; i < 10; i++) {
            count[i] += count[i - 1];
        }

        for (let i = arr.length - 1; i >= 0; i--) {

            let index = Math.floor(arr[i] / exp) % 10;
            output[count[index] - 1] = arr[i];
            count[index]--;

        }

        arr = output;
        exp *= 10;

    }

    return arr;

}

let items = [5, 123, 87, 9, 456, 12];

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

This version uses counting logic internally to keep the sort stable. Beginners can see how Radix Sort still works even when numbers have different sizes. It is useful for understanding how stability plays a role in sorting.

Program 5: Radix Sort in descending order

This program shows how Radix Sort can be adapted to sort numbers in descending order. It builds on the same logic with a small adjustment.

function radixSortDescending(arr) {

    let max = Math.max(...arr);
    let place = 1;

    while (Math.floor(max / place) > 0) {

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

        for (let i = 0; i < arr.length; i++) {
            let digit = Math.floor(arr[i] / place) % 10;
            buckets[digit].push(arr[i]);
        }

        arr = [].concat(...buckets.reverse());
        place *= 10;

    }

    return arr;

}

let scores = [34, 2, 122, 45, 98];

console.log("Sorted array (descending):", radixSortDescending(scores));

This program simply reverses the bucket order before merging them back. Beginners can learn how small changes can affect the final result. It is a good way to experiment and understand sorting order.

Program 6: Radix Sort that handles negative numbers

This program extends the basic Radix Sort to correctly handle negative numbers. Since standard Radix Sort works only with non-negative numbers, this version separates negative and positive values, sorts them individually, and then combines them back into one sorted array.

function radixSortWithNegatives(arr) {

    let negatives = [];
    let positives = [];

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

        if (arr[i] < 0) {
            negatives.push(Math.abs(arr[i]));
        } else {
            positives.push(arr[i]);
        }

    }

    function radixSortNonNegative(nums) {

        let max = Math.max(...nums, 0);
        let place = 1;

        while (Math.floor(max / place) > 0) {

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

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

                let digit = Math.floor(nums[i] / place) % 10;
                buckets[digit].push(nums[i]);

            }

            nums = [].concat(...buckets);
            place *= 10;

        }

        return nums;

    }

    positives = radixSortNonNegative(positives);
    negatives = radixSortNonNegative(negatives)
        .reverse()
        .map(num => -num);

    return negatives.concat(positives);

}

let numbers = [170, -45, 75, -90, 802, 24, -2, 66];

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

This program works by first splitting the array into negative and positive numbers. The negative numbers are converted to positive values so Radix Sort can process them normally. After sorting, the negative values are reversed and converted back to negative form before being combined with the sorted positive numbers. This approach is useful because it keeps Radix Sort simple while still supporting real-world data that includes negative values. Beginners can understand this by thinking of it as sorting two groups separately and then joining them back together in the correct order.

Frequently Asked Questions (FAQ)

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

Q1. What is Radix Sort in JavaScript?
Radix Sort is a sorting algorithm that sorts numbers by processing individual digits instead of comparing whole values.

Q2. Is Radix Sort faster than Quick Sort?
Radix Sort can be faster for large sets of numbers with fixed digit lengths, but Quick Sort is more flexible for general data.

Q3. Can Radix Sort sort negative numbers?
Basic Radix Sort works best with non-negative numbers. Extra logic is needed to handle negative values.

Q4. Where is Radix Sort used in real life?
Radix Sort is used in systems that sort IDs, phone numbers, and large numeric records.

Q5. Should beginners learn Radix Sort?
Yes, beginners should learn Radix Sort after basic algorithms. It teaches a new way of thinking about sorting.

Conclusion

Radix Sort is a unique and powerful sorting algorithm that shows beginners there is more than one way to organize data. By sorting numbers digit by digit, it avoids direct comparisons and achieves impressive speed in the right situations. Learning Radix Sort in JavaScript also strengthens understanding of loops, math operations, and algorithm design.

The best way to master Radix Sort is to practice with different numbers and variations. Try sorting larger arrays, changing the order, or adding support for negative numbers. With regular practice, Radix Sort will become another strong tool in your JavaScript programming skills.

Scroll to Top