Radix Sort Visualization
Speed:
Step: 0 / -1Algorithm Code
1function radixSort(arr) {
2 // Find the maximum number to know the number of digits
3 const max = Math.max(...arr);
4
5 // Do counting sort for every digit
6 // Instead of passing a digit number, exp is passed
7 // exp is 10^i where i is the current digit number
8 for (let exp = 1; Math.floor(max / exp) > 0; exp *= 10) {
9 countingSortByDigit(arr, exp);
10 }
11
12 return arr;
13 }
14
15 function countingSortByDigit(arr, exp) {
16 const n = arr.length;
17
18 // Create output array
19 const output = new Array(n).fill(0);
20
21 // Create count array for digits 0-9
22 const count = new Array(10).fill(0);
23
24 // Store count of occurrences in count[]
25 for (let i = 0; i < n; i++) {
26 const digit = Math.floor(arr[i] / exp) % 10;
27 count[digit]++;
28 }
29
30 // Change count[i] so that count[i] now contains
31 // actual position of this digit in output[]
32 for (let i = 1; i < 10; i++) {
33 count[i] += count[i - 1];
34 }
35
36 // Build the output array
37 for (let i = n - 1; i >= 0; i--) {
38 const digit = Math.floor(arr[i] / exp) % 10;
39 output[count[digit] - 1] = arr[i];
40 count[digit]--;
41 }
42
43 // Copy the output array to arr[], so that arr[] now
44 // contains sorted numbers according to current digit
45 for (let i = 0; i < n; i++) {
46 arr[i] = output[i];
47 }
48 }Visualization