Skip to content

Instantly share code, notes, and snippets.

@mrblueblue
Created January 5, 2018 22:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrblueblue/d10c1f692412c7210123157480bd5f44 to your computer and use it in GitHub Desktop.
Save mrblueblue/d10c1f692412c7210123157480bd5f44 to your computer and use it in GitHub Desktop.
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