How it works
Sorts by processing digits from least significant to most significant, using counting sort as a subroutine.
Implementation
function radixSort(arr) { const max = Math.max(...arr); for (let exp = 1; Math.floor(max/exp) > 0; exp *= 10) { const buckets = Array.from({length: 10}, () => []); for (const v of arr) buckets[Math.floor(v/exp) % 10].push(v); let idx = 0; for (const b of buckets) for (const v of b) arr[idx++] = v; } }
def radix_sort(arr): mx = max(arr) exp = 1 while mx // exp > 0: buckets = [[] for _ in range(10)] for v in arr: buckets[(v // exp) % 10].append(v) idx = 0 for b in buckets: for v in b: arr[idx] = v; idx += 1 exp *= 10
void radixSort(vector<int>& arr) { int mx = *max_element(arr.begin(), arr.end()); for (int exp = 1; mx/exp > 0; exp *= 10) { vector<vector<int>> buckets(10); for (int v : arr) buckets[(v/exp) % 10].push_back(v); int idx = 0; for (auto& b : buckets) for (int v : b) arr[idx++] = v; } }
void RadixSort(int[] arr) { int max = arr.Max(); for (int exp = 1; max/exp > 0; exp *= 10) { var buckets = Enumerable.Range(0,10) .Select(_ => new List<int>()).ToArray(); foreach (int v in arr) buckets[(v/exp) % 10].Add(v); int idx = 0; foreach (var b in buckets) foreach (int v in b) arr[idx++] = v; } }
void radixSort(int arr[], int n) { int max = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > max) max = arr[i]; for (int exp = 1; max/exp > 0; exp *= 10) { int output[n], count[10] = {0}; for (int i = 0; i < n; i++) count[(arr[i]/exp)%10]++; for (int i = 1; i < 10; i++) count[i] += count[i-1]; for (int i = n-1; i >= 0; i--) output[--count[(arr[i]/exp)%10]] = arr[i]; for (int i = 0; i < n; i++) arr[i] = output[i]; } }