From e29466aab9315a98206be04aee05c15cdd6f65af Mon Sep 17 00:00:00 2001 From: mehul Date: Wed, 17 Aug 2022 10:15:13 +0530 Subject: [PATCH] radix sort using javascript --- .../JavaScript/src/sorting/radix-sort.js | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 algorithms/JavaScript/src/sorting/radix-sort.js diff --git a/algorithms/JavaScript/src/sorting/radix-sort.js b/algorithms/JavaScript/src/sorting/radix-sort.js new file mode 100644 index 00000000..cdb5d83f --- /dev/null +++ b/algorithms/JavaScript/src/sorting/radix-sort.js @@ -0,0 +1,44 @@ +const countingSortNegative = (arr, n, place) => { + let max = Math.max(...arr); + let min = Math.min(...arr); + let range = max - min + 1; + let count = new Array(range).fill(0); + let output = new Array(n).fill(0); + + //Store the frequency + for (let i = 0; i < n; i++) { + const num = Math.floor(arr[i] / place) % 10; + count[num - min]++; + } + + //Accumulate the frequency + for (let i = 1; i < count.length; i++) { + count[i] += count[i - 1]; + } + + //Sort based on frequency + for (let i = n - 1; i >= 0; i--) { + const num = Math.floor(arr[i] / place) % 10; + output[count[num - min] - 1] = arr[i]; + count[num - min]--; + } + + //Copy the output array + for (let i = 0; i < n; i++){ + arr[i] = output[i]; + } + } + + const radixSort = (arr, size = arr.length) => { + //Get the max element + let max = Math.max(...arr); + + //Sort the array using counting sort + for(let i = 1; parseInt(max / i) > 0; i *= 10){ + countingSortNegative(arr, size, i); + } + } + + const arr = [121, -432, 564, 23, -1, 45, 788]; + radixSort(arr); + console.log(arr); \ No newline at end of file