NOIDATUT FREE E LEARNING PLATFORM • AKTU B.TECH

Radix Sorting in Data Structure

Radix sort is a non-comparison sorting algorithm that sorts integers or fixed-length strings digit by digit or character by character, from least significant to most significant (LSD) or vice versa, using a stable subroutine like counting sort.


Theory & Explanation

Radix Sort: Definition, Stepwise Working, Complexity & Code

1. Definition & Key Characteristics

Radix Sort is a non-comparison-based sorting algorithm that sorts numbers (or fixed-length keys) by processing individual digits or characters one place at a time, typically starting from the Least Significant Digit (LSD) (ones place) to the Most Significant Digit (MSD) (highest place), using a stable sorting subroutine—most commonly Counting Sort—at each digit position.

  • Non-Comparison Sorting: Avoids direct element-to-element key comparisons; instead, it groups and orders elements by digit values (0 to 9 for decimal numbers).
  • Requires a Stable Subroutine: Each digit pass must preserve the relative order of elements that have the same digit at the current place; otherwise, earlier digit ordering is lost.
  • Linear-Time Potential for Bounded Digits: Runs in O(d · (n + b)) time, where n is the number of elements, d is the number of digits in the maximum element, and b is the radix/base (e.g., b = 10 for base-10 integers).
  • Not In-Place: Needs extra auxiliary space for count arrays and temporary output arrays during each pass.

2. How Radix Sort Works (LSD Step-by-Step Algorithm)

  1. Find Maximum Element: Scan the array to find maxVal so we know how many digit positions d exist.
  2. Loop Over Digit Places: Set place value exp = 1 (ones place). While maxVal / exp > 0:
    • Perform a stable Counting Sort on the array based on the current digit: digit = (arr[i] / exp) % 10.
    • Multiply exp by 10 (exp = exp 10) to move to tens, hundreds, and higher places.
  3. Completion: Once all digit places up to the most significant digit of maxVal have been stably sorted, the entire array is sorted in ascending order.

3. Step-by-Step Example & Graphical Representation

Sort arr = [170, 45, 75, 90, 802, 24, 2, 66] (n = 8, maxVal = 802 → 3 passes: exp = 1, 10, 100) in ascending order:

  • Pass 1 (exp = 1, Ones Digit): Digits are 0, 5, 5, 0, 2, 4, 2, 6. Stable grouping by ones digit gives: [170, 90, 802, 2, 24, 45, 75, 66].
  • Pass 2 (exp = 10, Tens Digit — leading zero for 2): Tens digits are 7, 9, 0, 0, 2, 4, 7, 6. Stable grouping by tens digit gives: [802, 2, 24, 45, 66, 170, 75, 90].
  • Pass 3 (exp = 100, Hundreds Digit — leading zeros for 2-digit & 1-digit numbers): Hundreds digits are 8, 0, 0, 0, 0, 1, 0, 0. Stable grouping by hundreds digit gives: [2, 24, 45, 66, 75, 90, 170, 802].

Graphical Representation: Stepwise LSD Passes on [170, 45, 75, 90, 802, 24, 2, 66]

Radix Sort (LSD) Trace: Ones (exp=1) → Tens (exp=10) → Hundreds (exp=100)
Initial Array
[170, 45, 75, 90, 802, 24, 2, 66]
Pass 1: Sort by Ones Digit (exp = 1)
[170, 90, 802, 2, 24, 45, 75, 66]
Pass 2: Sort by Tens Digit (exp = 10)
[802, 02, 24, 45, 66, 170, 75, 90]
Pass 3: Sort by Hundreds Digit (exp = 100) — Final Sorted Output
[002, 024, 045, 066, 075, 090, 170, 802] → [2, 24, 45, 66, 75, 90, 170, 802]

4. Time & Space Complexity Analysis

Metric Complexity Exam Explanation
Best, Average & Worst Time O(d · (n + b)) d passes; each pass runs stable counting sort over n elements and base b (b = 10 for decimal)
When d Is Constant & b = O(1) O(n) Linear time when numbers have a fixed maximum number of digits
Auxiliary Space O(n + b) Temporary output array of size n plus frequency/count array of size b

5. C Program: Radix Sort (LSD with Counting Sort)

#include <stdio.h>

int getMax(int arr[], int n) {
    int mx = arr[0];
    for (int i = 1; i < n; i++) {
        if (arr[i] > mx)
            mx = arr[i];
    }
    return mx;
}

void countingSortByDigit(int arr[], int n, int exp) {
    int output[n];
    int count[10] = {0};

    // Count occurrences of each digit at current place (exp)
    for (int i = 0; i < n; i++) {
        int digit = (arr[i] / exp) % 10;
        count[digit]++;
    }

    // Cumulative counts to compute positions
    for (int i = 1; i < 10; i++) {
        count[i] += count[i - 1];
    }

    // Build output array from right to left to maintain stability
    for (int i = n - 1; i >= 0; i--) {
        int digit = (arr[i] / exp) % 10;
        output[count[digit] - 1] = arr[i];
        count[digit]--;
    }

    // Copy back to arr[]
    for (int i = 0; i < n; i++) {
        arr[i] = output[i];
    }
}

void radixSort(int arr[], int n) {
    int m = getMax(arr, n);
    for (int exp = 1; m / exp > 0; exp = 10) {
        countingSortByDigit(arr, n, exp);
    }
}

void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("Original array: ");
    printArray(arr, n);

    radixSort(arr, n);

    printf("Sorted array (Ascending): ");
    printArray(arr, n);

    return 0;
}

Expected Output (C):

Original array: 170 45 75 90 802 24 2 66 
Sorted array (Ascending): 2 24 45 66 75 90 170 802 

6. Python Program: Radix Sort

def counting_sort_by_digit(arr, exp):
    n = len(arr)
    output = [0]  n
    count = [0]  10

    for num in arr:
        digit = (num // exp) % 10
        count[digit] += 1

    for i in range(1, 10):
        count[i] += count[i - 1]

    for i in range(n - 1, -1, -1):
        digit = (arr[i] // exp) % 10
        output[count[digit] - 1] = arr[i]
        count[digit] -= 1

    return output


def radix_sort(arr):
    if not arr:
        return []

    a = arr[:]
    max_val = max(a)
    exp = 1

    while max_val // exp > 0:
        a = counting_sort_by_digit(a, exp)
        exp *= 10

    return a


if __name__ == "__main__":
    data = [170, 45, 75, 90, 802, 24, 2, 66]
    print("Original array:", data)
    print("Sorted array (Ascending):", radix_sort(data))

Expected Output (Python):

Original array: [170, 45, 75, 90, 802, 24, 2, 66]
Sorted array (Ascending): [2, 24, 45, 66, 75, 90, 170, 802]
Advertisement
Advertisement