Created
April 23, 2019 08:16
-
-
Save 4skinSkywalker/a48316ec74681b160f0a4c6fef98e9d9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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