From 23868e198aa02c3eea47a7aa9a573336f4c7a262 Mon Sep 17 00:00:00 2001 From: Nauman Ahmad Date: Sat, 19 Oct 2019 12:40:01 +0500 Subject: [PATCH] Add Radix sort --- src/algorithms/sorting/radixSort.js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 src/algorithms/sorting/radixSort.js diff --git a/src/algorithms/sorting/radixSort.js b/src/algorithms/sorting/radixSort.js new file mode 100644 index 0000000..3541c9d --- /dev/null +++ b/src/algorithms/sorting/radixSort.js @@ -0,0 +1,20 @@ +function radixSort(arr) { + // Find the max number and multiply it by 10 to get a number + // with no. of digits of max + 1 + const maxNum = Math.max(...arr) * 10; + let divisor = 10; + while (divisor < maxNum) { + // Create bucket arrays for each of 0-9 + let buckets = [...Array(10)].map(() => []); + // For each number, get the current significant digit and put it in the respective bucket + for (let num of arr) { + buckets[Math.floor((num % divisor) / (divisor / 10))].push(num); + } + // Reconstruct the array by concatinating all sub arrays + arr = [].concat.apply([], buckets); + // Move to the next significant digit + divisor *= 10; + } + return arr; + } + console.log(radixSort([5,3,88,235,65,23,4632,234])) \ No newline at end of file