Skip to content

Commit a4fa364

Browse files
author
hojas
committed
sort
1 parent 19ef0e8 commit a4fa364

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
7. [Heap Sort](https://github.com/hojas/typescript-algorithms/tree/main/src/2-algorithms/1-sort/7-heap-sort)
2121
8. [Counting Sort](https://github.com/hojas/typescript-algorithms/tree/main/src/2-algorithms/1-sort/8-counting-sort)
2222
9. [Bucket Sort](https://github.com/hojas/typescript-algorithms/tree/main/src/2-algorithms/1-sort/9-bucket-sort)
23+
10. [Radix Sort](https://github.com/hojas/typescript-algorithms/tree/main/src/2-algorithms/1-sort/10-radix-sort)
2324

2425
### Search
2526

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { describe, expect, it } from 'vitest'
2+
import { radixSort } from './radix-sort'
3+
4+
describe('radix Sort', () => {
5+
it('should sort an array of numbers', () => {
6+
const nums = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
7+
const expected = [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
8+
const actual = radixSort(nums)
9+
expect(actual).to.deep.equal(expected)
10+
})
11+
})
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* Radix Sort
3+
*
4+
* O(n * k)
5+
* Stable
6+
*
7+
* @param nums
8+
* @returns nums
9+
*
10+
*/
11+
export function radixSort(nums: number[]): number[] {
12+
const max = Math.max(...nums)
13+
const digits = Math.floor(Math.log10(max)) + 1
14+
15+
for (let i = 0; i < digits; i++) {
16+
const buckets: number[][] = Array.from({ length: 10 }, () => [])
17+
18+
for (let j = 0; j < nums.length; j++) {
19+
const digit = Math.floor((nums[j] / 10 ** i) % 10)
20+
buckets[digit].push(nums[j])
21+
}
22+
23+
nums = buckets.flat()
24+
}
25+
26+
return nums
27+
}

0 commit comments

Comments
 (0)