Radix sort is a non-comparative sorting algorithm that sorts integers by grouping numbers by their individual digits.
It sorts numbers by processing digits from the least significant digit (LSD) to the most significant digit (MSD).
Radix sort can be implemented with various bases, but the most common are binary (base 2), decimal (base 10), and hexadecimal (base 16).
pseudocode:
radixSort(arr):
max_num = findMax(arr)
exp = 1
while max_num / exp > 0:
bucket = [[] for _ in range(10)]
for i in arr:
bucket[(i // exp) % 10].append(i)
arr = [j for sub in bucket for j in sub]
exp *= 10
return arr
findMax(arr):
max_num = arr[0]
for num in arr:
if num > max_num:
max_num = num
return max_num
functionfindMax(arr) {let max = arr[0];for (let i =1; i <arr.length; i++) {if (arr[i] > max) { max = arr[i]; } }return max;}// Radix Sort functionfunctionRadixSort(arr) {constmax=findMax(arr);let exp =1;while (max / exp >0) {constbucket=Array.from({ length:10 }, () => []);for (let i =0; i <arr.length; i++) {constdigit=Math.floor(arr[i] / exp) %10; bucket[digit].push(arr[i]); } arr = [].concat(...bucket); exp *=10; }return arr;}console.log(RadixSort(numbers));
This implementation of Radix Sort first determines the maximum number of digits in the array.
Then, it iterates through each digit position from the least significant to the most significant, placing the numbers into buckets based on the value of the digit at that position.
Finally, it concatenates the buckets to form the sorted array.