diff --git a/src/algorithms/sorting/radix-sort.js b/src/algorithms/sorting/radix-sort.js new file mode 100644 index 00000000..5e6bd356 --- /dev/null +++ b/src/algorithms/sorting/radix-sort.js @@ -0,0 +1,25 @@ +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; + } +// unit test +console.log(radixSort([5,3,88,235,65,23,4632,234])) +// unit test 2 +console.log(radixSort([802, 630, 20, 745, 52, 300, 612, 932, 78, 187])) +// unit test 3 +console.log(radixSort([45, 2, 56, 2, 5, 6, 34, 1, 56, 89, 33])) \ No newline at end of file diff --git a/src/algorithms/sorting/radix-sort.test.js b/src/algorithms/sorting/radix-sort.test.js new file mode 100644 index 00000000..1de06da3 --- /dev/null +++ b/src/algorithms/sorting/radix-sort.test.js @@ -0,0 +1,35 @@ +const radixSort = require('./radix-sort'); + +describe('Testing Radix Sort Algorithm', () => { + it('should sort with multiple digit elements #1', () => { + expect(radixSort([5,3,88,235,65,23,4632,234])).toEqual([3,5,23,65,88,234,235,4632]); + }); + + it('should sort with multiple digit elements #2', () => { + expect(radixSort([802,630,20,745,52,300,612,932,78,187])).toEqual([20,52,78,187,300,612,630,802,932]); + }); + + it('should sort with duplicated values', () => { + expect(radixSort([45,2,56,2,5,6,34,1,56,89,33])).toEqual([1,2,2,5,6,33,34,45,56,56,89]); + }); + + it('should work with zero numbers', () => { + expect(radixSort([])).toEqual([]); + }); + + it('should work with one number', () => { + expect(radixSort([3])).toEqual([3]); + }); + + it('should sort numbers', () => { + expect(radixSort([3, 5, 0])).toEqual([0, 3, 5]); + }); + + it('should sort with inverse array', () => { + expect(radixSort([3, 2, 1])).toEqual([1, 2, 3]); + }); + + it('should sort with already sorted array', () => { + expect(radixSort([1, 2, 3])).toEqual([1, 2, 3]); + }); +}); \ No newline at end of file