-
Notifications
You must be signed in to change notification settings - Fork 0
/
radix_sort.js
56 lines (44 loc) · 1.27 KB
/
radix_sort.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
const radixSort = (list) => {
const count = maxDigits(list);
let sorted = stringify(list);
for(let i = 0; i < count; ++i) {
sorted = bucketize(sorted, count - 1 - i).flat();
}
return sorted.map(x => parseInt(x));
};
const bucketize = (list, position) => {
return [...Array(10).keys()].map( i => list.filter(x => x.charAt(position) == i));
};
const stringify = (list) => {
const length = maxDigits(list)
return list.map(number => {
const prefix = '0'.repeat(length - String(number).length);
return `${prefix}${number}`;
});
};
const maxDigits = (list) => {
const max = list.reduce((x, y) => Math.max(x, y), list[0]);
return String(max).length;
};
const unitTest = () => {
const testCases = [
[
[170, 45, 75, 90, 2, 802, 2, 66],
[2, 2, 45, 66, 75, 90, 170, 802]
],
[
[8902, 67_832, 12, 1000, 4_002],
[12, 1000, 4_002, 8902, 67_832]
]
];
testCases.forEach(testCase => {
const [originalArray, expectedResult] = testCase;
const result = radixSort(originalArray);
const equal = JSON.stringify(result) == JSON.stringify(expectedResult);
console.log(equal ? 'Worked well for' : 'Failed on');
console.log(originalArray);
console.log(result);
console.log('--------')
});
}
unitTest();