Skip to content
Home ยป Radix Sort

Radix Sort


๐Ÿ“˜ Radix Sort (with Running Time Analysis)

1๏ธโƒฃ Introduction

Radix Sort is a non-comparison-based sorting algorithm used for sorting numbers digit by digit.

๐Ÿ”น Idea

  • Sort numbers based on individual digits
  • Start from:
    • Least Significant Digit (LSD) โ†’ most common
    • or Most Significant Digit (MSD)

It uses a stable sorting algorithm (like Counting Sort) as a subroutine.


2๏ธโƒฃ Working Principle

๐Ÿ”น Steps (LSD Method)

  1. Sort elements based on units place
  2. Then sort based on tens place
  3. Then hundreds place, and so on
  4. Continue until all digits are processed

โœ” Maintain stability at each step


3๏ธโƒฃ Algorithm (Radix Sort)

๐Ÿ”น Pseudocode

RadixSort(A, n):
   max = maximum element in A

   for exp = 1; max/exp > 0; exp = exp * 10:
       CountingSort(A, n, exp)

๐Ÿ”น Counting Sort (for each digit)

CountingSort(A, n, exp):
   create output array
   create count[10] initialized to 0

   for i = 0 to n-1:
       index = (A[i] / exp) % 10
       count[index]++

   compute cumulative count

   for i = n-1 to 0:
       index = (A[i] / exp) % 10
       output[count[index] - 1] = A[i]
       count[index]--

   copy output to A

4๏ธโƒฃ Example (Step-by-Step)

๐Ÿ”น Given Array:

A = [170, 45, 75, 90, 802, 24, 2, 66]

๐Ÿ”น Step 1: Sort by Units Place

[170, 90, 802, 2, 24, 45, 75, 66]

๐Ÿ”น Step 2: Sort by Tens Place

[802, 2, 24, 45, 66, 170, 75, 90]

๐Ÿ”น Step 3: Sort by Hundreds Place

[2, 24, 45, 66, 75, 90, 170, 802]

โœ” Final Sorted Array


5๏ธโƒฃ Running Time Analysis

๐Ÿ”น Let:

  • n = number of elements
  • d = number of digits
  • k = range of digits (0โ€“9 โ†’ k = 10)

๐Ÿ”น Time Complexity:

[
O(d \cdot (n + k))
]

Since k = 10 (constant):
[
O(d \cdot n)
]


6๏ธโƒฃ Time Complexity Cases

CaseComplexity
Best CaseO(dn)
Average CaseO(dn)
Worst CaseO(dn)

โœ” Same in all cases


7๏ธโƒฃ Space Complexity

  • O(n + k)
  • Requires extra memory for counting sort

8๏ธโƒฃ Characteristics of Radix Sort

โœ” Non-comparison-based
โœ” Stable sorting algorithm
โœ” Works on integers or fixed-length keys
โœ” Very fast for large datasets


9๏ธโƒฃ Advantages

  • Faster than comparison sorts for large data
  • Linear time complexity (for fixed digits)
  • Stable sorting

๐Ÿ”Ÿ Disadvantages

  • Extra memory required
  • Not suitable for:
    • Floating-point numbers (directly)
    • Variable-length data
  • Depends on digit count

1๏ธโƒฃ1๏ธโƒฃ Comparison with Other Sorting Algorithms

AlgorithmTime ComplexityType
Radix SortO(dn)Non-comparison
Merge SortO(n log n)Comparison
Quick SortO(n log n) avgComparison

๐Ÿ”š Conclusion

Radix Sort is a highly efficient sorting algorithm for numbers with fixed digit lengths.

It sorts data digit by digit using a stable sorting method, achieving near-linear time complexity.


๐Ÿ“Œ Exam Tip

๐Ÿ‘‰ Always include:

  • Digit-wise sorting explanation
  • Counting sort usage
  • Time complexity formula
  • Example