Skip to content

Instantly share code, notes, and snippets.

@4skinSkywalker
Created April 23, 2019 08:16
Show Gist options
  • Save 4skinSkywalker/a48316ec74681b160f0a4c6fef98e9d9 to your computer and use it in GitHub Desktop.
Save 4skinSkywalker/a48316ec74681b160f0a4c6fef98e9d9 to your computer and use it in GitHub Desktop.
function getDigit(n, i) {
n = Math.abs(n)
return (n / 10 ** i | 0) % 10
}
function countDigit(n) {
if (n === 0) {
return 1
}
n = Math.abs(n)
return Math.ceil(Math.log10(n + 1))
}
function radixSort(integers) {
let maxDigits = 0
for (let n of integers) {
maxDigits = Math.max(maxDigits, countDigit(n))
}
let buckets = [...Array(10)].map(_ => [])
for (let i = 0; i < maxDigits + 1; i++) {
for (let n of integers) {
buckets[getDigit(n, i)].push(n)
}
integers = buckets.flat(1)
buckets = [...Array(10)].map(_ => [])
}
return integers
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment