Skip to content

Instantly share code, notes, and snippets.

@Shaddyjr
Created October 25, 2019 02:18
Show Gist options
  • Save Shaddyjr/dba8a49655110d211ca5e3a75cb45165 to your computer and use it in GitHub Desktop.
Save Shaddyjr/dba8a49655110d211ca5e3a75cb45165 to your computer and use it in GitHub Desktop.
// https://www.youtube.com/watch?v=XiuSW_mEn7g
// maxLen = 3 = numOfIterations
// 110, 5, 70...
// [ [110,70], [], [], [], [], [5], [], [], [], [] ]
// [ [5], [110], [], [], [], [], [], [70], [], [] ]
// [ [5,70], [110], [], [], [], [], [], [], [], [] ]
// 5, 70, 110
function createSortingArray(base = 10){
return Array.from({length : base}, () => []);
}
function radixSort(arr){
let max = -Infinity;
for(const num of arr) max = Math.max(max, num); // O(n)
let prevSortingArray = [arr];
let iterations = String(max).length; // len(max digit) = d
let i = 0;
while(i < iterations){ // O(n * d)
let currentSortingArray = createSortingArray(); // len = k
const getDigit = function(num){
return Math.floor(num / Math.pow(10,i)) % 10;
}
for(const subArr of prevSortingArray){
for(const num of subArr) currentSortingArray[getDigit(num)].push(num);
}
i++;
prevSortingArray = currentSortingArray;
}
// flatten and return
return prevSortingArray.reduce((acc, val) => acc.concat(val), []); // O(n)
}
// range 0 - 999, all positive numbers and integers
const arr = [23,235,76,523,213,4,646,8,55,42,3,0,999,234,457,7,23];
console.log(radixSort(arr));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment