const getDigits = (num, i) => { return Math.floor(Math.abs(num)/ Math.pow(10,i)%10) } const digitCount = (num) => { if(num === 0) return 1 return Math.floor(Math.log10(Math.abs(num)) + 1) } const mostDigits = (num) => { let maxDigit = 0 for(let i = 0; i< num.length; i++) { maxDigit = Math.max(maxDigit, digitCount(num[i])) } return maxDigit } const radixSort = (nums) => { const maxDigit = mostDigits(nums); for(let k = 0; k < maxDigit; k++) { let digitBucket = Array.from({length: 10}, () => []) for(let i = 0; i< nums.length; i++) { const digit = getDigits(nums[i], k) digitBucket[digit].push(nums[i]); } nums = [].concat(...digitBucket) } return nums } radixSort([32,54,1212,5434534,545645])
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter