|
| 1 | +const getNthDigit = (number, n) => { |
| 2 | + for (let i = 0; i < n; i++) { |
| 3 | + number = Math.floor(number / 10); |
| 4 | + } |
| 5 | + return number % 10; |
| 6 | +}; |
| 7 | + |
| 8 | +const shouldStop = (array, dictionary) => { |
| 9 | + return dictionary.hasOwnProperty(0) && array.length === dictionary[0].length; |
| 10 | +}; |
| 11 | + |
| 12 | +const extractElements = dictionary => { |
| 13 | + return Object.keys(dictionary).reduce((elements, key) => { |
| 14 | + return dictionary[key] ? elements.concat(dictionary[key]) : elements; |
| 15 | + }, []); |
| 16 | +}; |
| 17 | + |
| 18 | +const radixSort = array => { |
| 19 | + let index = 0; |
| 20 | + while (true) { |
| 21 | + const dictionary = array.reduce((dict, element) => { |
| 22 | + const digit = getNthDigit(element, index); |
| 23 | + const elements = dict[digit] || []; |
| 24 | + dict[digit] = elements.concat(element); |
| 25 | + return dict; |
| 26 | + }, {}); |
| 27 | + const extractedElements = extractElements(dictionary); |
| 28 | + array.length = 0; |
| 29 | + array.push(...extractedElements); |
| 30 | + if (shouldStop(array, dictionary)) { |
| 31 | + break; |
| 32 | + } |
| 33 | + index++; |
| 34 | + } |
| 35 | +}; |
| 36 | + |
| 37 | +const array = [10, 21, 17, 34, 44, 11, 654, 123]; |
| 38 | +radixSort(array); |
| 39 | +console.log(array); |
0 commit comments