Radix sort - JavaScript


Radix Sort 

Radix sort is a sorting algorithm that sorts data with integer keys by grouping keys by the individual digits which share the same significant position and value.

We are required to write a JavaScript function that takes in an array of literals as the only argument. The function should sort the array in either increasing or decreasing order using the radix sort algorithm.

Example

Following is the code −

const arr = [45, 2, 56, 2, 5, 6, 34, 1, 56, 89, 33];
const radixSort = (arr = []) => {
   const base = 10;
   let divider = 1;
   let maxVal = Number.NEGATIVE_INFINITY;
   while (divider === 1 || divider <= maxVal) {
      const buckets = [...Array(10)].map(() => []);
      for (let val of arr) {
         buckets[Math.floor((val / divider) % base)].push(val);
         maxVal = val > maxVal ? val : maxVal;
      }
      arr = [].concat(...buckets);
      divider *= base;
   };
   return arr;
};
console.log(radixSort(arr));

Output

Following is the output on console −

[
   1, 2, 2, 5, 6,
   33, 34, 45, 56, 56,
   89
]

Updated on: 11-Dec-2020

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements