Skip to content

Commit a81a2bc

Browse files
committed
Add Radix Sort test
1 parent 60c4c33 commit a81a2bc

File tree

2 files changed

+32
-15
lines changed

2 files changed

+32
-15
lines changed

src/sort/radixSort.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import radixSort from "./radixSort";
2+
3+
describe("Radix Sort Test", () => {
4+
test("Testing if RS sort a random array", () => {
5+
const nTimes = 100;
6+
const SIZE = 100;
7+
for (let i = 0; i < nTimes; i++) {
8+
const arr = Array.from({ length: SIZE }, () =>
9+
Math.floor(Math.random() * 1000)
10+
);
11+
const sortedArr = radixSort(arr);
12+
const jsSortedArr = arr.slice().sort((a, b) => a - b);
13+
expect(sortedArr).toEqual(jsSortedArr);
14+
}
15+
});
16+
});

src/sort/radixSort.ts

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,34 +7,35 @@ const getDigit = (num: number, place: number) => {
77
const digitCount = (num: number) => {
88
// log 0
99
if (num === 0) return 1;
10-
return Math.floor(Math.log10(num)) + 1;
10+
return Math.floor(Math.log10(Math.abs(num))) + 1;
1111
};
1212

13-
// returns the number of digits in the largest number of the list nums
14-
const mostDigits = (nums: number[]) => {
13+
// returns the number of digits in the largest number of the list arr
14+
const maximumDigits = (arr: number[]) => {
1515
let max = 0;
16-
for (let i = 0; i < nums.length; i++) {
17-
max = Math.max(max, nums[i]);
16+
for (let n of arr) {
17+
max = Math.max(max, digitCount(n));
1818
}
19+
1920
return max;
2021
};
2122

22-
const radixSort = (nums: number[]) => {
23-
let maxDigits = mostDigits(nums);
23+
const radixSort = (arr: number[]) => {
24+
let maxDigits = maximumDigits(arr);
2425
// put each digit from each num in the right bucket
2526
for (let i = 0; i < maxDigits; i++) {
2627
// an array of 10 empty arrays, a bucket to each possible number
2728
let digitBuckets: number[][] = Array.from({ length: 10 }, () => []);
28-
for (let j = 0; j < nums.length; j++) {
29-
// take the digit of nums[j]
30-
let digit = getDigit(nums[j], i);
31-
// add this nums[j] in the bucket of the right digit
32-
digitBuckets[digit].push(nums[j]);
29+
for (let j = 0; j < arr.length; j++) {
30+
// take the digit of arr[j]
31+
let digit = getDigit(arr[j], i);
32+
// add this arr[j] in the bucket of the right digit
33+
digitBuckets[digit].push(arr[j]);
3334
}
3435
// to concate each element from each bucket, using spread
35-
nums = Array.prototype.concat(...digitBuckets);
36+
arr = Array.prototype.concat(...digitBuckets);
3637
}
37-
return nums;
38+
return arr;
3839
};
3940

40-
export = radixSort;
41+
export default radixSort;

0 commit comments

Comments
 (0)