-
Notifications
You must be signed in to change notification settings - Fork 1
/
RadixSort.js
66 lines (60 loc) · 1.71 KB
/
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// RadixSort
// mostly from https://jsben.ch/96YZc
// this version is nicely simple, but does another iteration through the array
// to find max: https://tylerewillis.com/page/radix-sort-javascript
/* test
arr = [1,3,3,4,2,1,3,7,20,99,42,41];
radixSortInt(arr)
arr = arr.map((elem, idx) => {
return { idx, score: elem};
});
radixSortObj(arr, "score")
*/
export function radixSortObj(arr, scoreProp) {
let maxNum = 0;
let place = 10;
let digit_counter = 0;
const ln = arr.length;
const buckets = [[], [], [], [], [], [], [], [], [], []];
for ( let i = 0; i < ln; i += 1 ) {
const num = arr[i][scoreProp];
buckets[num % 10].push(arr[i]);
maxNum = Math.max(num, maxNum);
}
const max = Math.log10(maxNum) | 0;
arr = [].concat(...buckets);
while ( digit_counter++ < max ) {
const buckets = [[], [], [], [], [], [], [], [], [], []];
for ( let i = 0; i < ln; i += 1 ) {
const num = arr[i][scoreProp];
buckets[(num / place | 0) % 10].push(arr[i]);
}
place *= 10;
arr = [].concat(...buckets);
}
return arr;
}
export function radixSortInt(arr) {
let maxNum = 0;
let place = 10;
let digit_counter = 0;
const ln = arr.length;
const buckets = [[], [], [], [], [], [], [], [], [], []];
for ( let i = 0; i < ln; i += 1 ) {
const num = arr[i];
buckets[num % 10].push(num);
maxNum = Math.max(num, maxNum);
}
const max = Math.log10(maxNum) | 0;
arr = [].concat(...buckets);
while ( digit_counter++ < max ) {
const buckets = [[], [], [], [], [], [], [], [], [], []];
for ( let i = 0; i < ln; i += 1 ) {
const num = arr[i];
buckets[(num / place | 0) % 10].push(num);
}
place *= 10;
arr = [].concat(...buckets);
}
return arr;
}