Created
January 5, 2018 22:57
-
-
Save mrblueblue/d10c1f692412c7210123157480bd5f44 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const digit = (num, pos) => { | |
const str = num.toString()[pos] | |
return typeof str === "undefined" ? 0 : parseInt(str) | |
} | |
const maxDigits = input => input.reduce((accum, value) => { | |
const len = value.toString().length | |
return accum < len ? len : accum | |
}, null) | |
const convertSorted = rad => rad.reduce((accum, value) => { | |
if (Array.isArray(value)) { | |
return accum.concat(value) | |
} else { | |
return accum | |
} | |
},[]) | |
const ex = [999, 10, 53, 194] | |
function radixSort(input) { | |
const numDigits = maxDigits(input) | |
let current = 0 | |
let rad = [] | |
let sorted = input | |
while (current <= numDigits) { | |
rad = [] | |
for (let i = 0; i < sorted.length; i++) { | |
const dig = digit(sorted[i], current) | |
if (typeof rad[dig] === "undefined") { | |
rad[dig] = [] | |
} | |
rad[dig].push(sorted[i]) | |
} | |
sorted = convertSorted(rad) | |
current++ | |
} | |
return sorted | |
} | |
console.log(radixSort(ex)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment