Radix Sort
A special sorting algorithm that it doesn't sorted by comparing the two items directly, instead it create ten digit buckets and store itmes from their digit and shift from 0. By doing these method in longest nums, the array will be sorted.
function getLongestNums(array){
let longestNum = 1
array.forEach((num)=> {
const targetLength = num.toString().length
if (target > longestNum){
longestNum = targetLength
}
})
return longestNum
}
function getDigit(num, round) {
const numStr = num.toString()
const lastIdx = numStr.length - 1
return numStr[lastIdx - round] ? numStr[lastIdx - round] : 0
}
function radixSort(items) {
//[2934, 3992, 294, 3, 1301242, 4, 400]
const maxLength = getLongestNums(items)
const buckets = new Array(10).fill().map(() => [])
for (let j = 0; j < maxLength; j++) {
while (items.length) {
const current = items.shift()
buckets[getDigit(current, j)].push(current)
}
for (let i = 0; i < 10; i++) {
while (buckets[i].length) {
items.push(buckets[i].shift())
}
}
}
return items
}