Skip to content

Commit 2ed46c2

Browse files
author
Cory Thompson
committed
implemented and tested radix sort
1 parent 64f4293 commit 2ed46c2

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed

sorting/radixsort/radixSort.test.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import { radixSort } from "./radixSort";
2+
3+
const fourDigitArray = [
4+
1234,
5+
5421,
6+
3323,
7+
4454,
8+
1111,
9+
2222,
10+
3333,
11+
5435,
12+
4545,
13+
2332,
14+
3215
15+
];
16+
17+
const fourDigitSortedArray = [
18+
1111,
19+
1234,
20+
2222,
21+
2332,
22+
3215,
23+
3323,
24+
3333,
25+
4454,
26+
4545,
27+
5421,
28+
5435
29+
];
30+
31+
test("radixSort", () => {
32+
expect(radixSort([1, 2, 3, 4])).toEqual([1, 2, 3, 4]);
33+
expect(radixSort([3, 2, 1, 4])).toEqual([1, 2, 3, 4]);
34+
expect(radixSort([2, 3, 4, 1])).toEqual([1, 2, 3, 4]);
35+
expect(radixSort([2, 3, 4, 1])).toEqual([1, 2, 3, 4]);
36+
expect(radixSort(fourDigitArray)).toEqual(fourDigitSortedArray);
37+
});

sorting/radixsort/radixSort.ts

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* Radix Sort implemented in TypeScript
3+
* https://github.com/AllAlgorithms/TypeScript
4+
*/
5+
6+
function maxPlaceValue(arr: number[]): number {
7+
let max = 0;
8+
for (const num of arr) {
9+
const digits = Math.floor(Math.log10(num) + 1);
10+
max = Math.max(max, digits);
11+
}
12+
13+
return max;
14+
}
15+
16+
function getDigit(num: number, place: number): number {
17+
return Math.floor(num / place) % 10;
18+
}
19+
20+
export function radixSort(arr: number[]): number[] {
21+
const digits = maxPlaceValue(arr);
22+
let sortedArray = arr.slice();
23+
for (let i = 1; i <= digits; i++) {
24+
const place = Math.pow(10, i - 1); // ones place, tens place, etc
25+
26+
// create empty bucket of 10 empty arrays
27+
const buckets: number[][] = [];
28+
for (let i = 0; i < 10; i++) {
29+
buckets.push([]);
30+
}
31+
32+
for (const num of sortedArray) {
33+
const digit = getDigit(num, place);
34+
buckets[digit].push(num);
35+
}
36+
37+
sortedArray = ([] as number[]).concat(...buckets);
38+
}
39+
40+
return sortedArray;
41+
}

0 commit comments

Comments
 (0)