Radix Sort
A non-comparative integer sorting algorithm that sorts data with integer keys by grouping keys by individual digits which share the same significant position and value. Radix sort dates back to 1887 to the work of Herman Hollerith on tabulating machines.
Visualization
Interactive visualization for Radix Sort
Radix Sort Visualization
Interactive visualization with step-by-step execution
Implementation
1function radixSort(arr: number[]): number[] {
2 if (arr.length === 0) return [];
3
4 const max = Math.max(...arr);
5 const sorted = [...arr];
6
7 for (let exp = 1; Math.floor(max / exp) > 0; exp *= 10) {
8 countingSortByDigit(sorted, exp);
9 }
10
11 return sorted;
12}
13
14function countingSortByDigit(arr: number[], exp: number): void {
15 const n = arr.length;
16 const output = new Array(n);
17 const count = new Array(10).fill(0);
18
19 for (let i = 0; i < n; i++) {
20 const digit = Math.floor(arr[i] / exp) % 10;
21 count[digit]++;
22 }
23
24 for (let i = 1; i < 10; i++) {
25 count[i] += count[i - 1];
26 }
27
28 for (let i = n - 1; i >= 0; i--) {
29 const digit = Math.floor(arr[i] / exp) % 10;
30 output[count[digit] - 1] = arr[i];
31 count[digit]--;
32 }
33
34 for (let i = 0; i < n; i++) {
35 arr[i] = output[i];
36 }
37}Deep Dive
Theoretical Foundation
Radix sort processes integers digit by digit, starting from the least significant digit to the most significant digit. It uses a stable sorting algorithm (typically counting sort) as a subroutine to sort on each digit position.
Complexity
Time
O(d × (n + k))
O(d × (n + k))
O(d × (n + k))
Space
O(n + k)
Applications
Use Cases
Related Algorithms
Quicksort
A highly efficient, in-place sorting algorithm that uses divide-and-conquer strategy. Invented by Tony Hoare in 1959, it remains one of the most widely used sorting algorithms due to its excellent average-case performance and cache efficiency.
Merge Sort
A stable, divide-and-conquer sorting algorithm with guaranteed O(n log n) performance.
Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order. This process is repeated until the entire array is sorted. Named for the way larger elements 'bubble' to the top (end) of the array.
Insertion Sort
Insertion Sort is a simple, intuitive sorting algorithm that builds the final sorted array one element at a time. It works similarly to how people sort playing cards in their hands - picking each card and inserting it into its correct position among the already sorted cards. Despite its O(n²) time complexity, Insertion Sort is efficient for small datasets and nearly sorted arrays, making it practical for real-world applications.