-
Notifications
You must be signed in to change notification settings - Fork 2
/
RadixSort.js
40 lines (32 loc) · 931 Bytes
/
RadixSort.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const countingSort = (arr, size, place) => {
let output = new Array(size + 1).fill(0);
let max = Math.max(...arr);
let freq = new Array(max + 1).fill(0);
// Calculate count of elements
for (let i = 0; i < size; i++){
const num = Math.floor(arr[i] / place) % 10;
freq[num]++;
}
// Calculate cummulative count
for (let i = 1; i < 10; i++){
freq[i] += freq[i - 1];
}
// Place the elements in sorted order
for (let i = size - 1; i >= 0; i--) {
const num = Math.floor(arr[i] / place) % 10;
output[freq[num] - 1] = arr[i];
freq[num]--;
}
//Copy the output array
for (let i = 0; i < size; i++){
arr[i] = output[i];
}
}
const radixSort = (arr, size = arr.length) => {
//Get the max element
let max = Math.max(...arr);
//Sort the array using counting sort
for(let i = 1; parseInt(max / i) > 0; i *= 10){
countingSort(arr, size, i);
}
}