Skip to content

Commit 67e94ef

Browse files
author
Adithya
committed
Radix sort in javascript
1 parent 02d9f48 commit 67e94ef

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/algorithms/sorting/radix-sort.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
function radixSort(arr) {
2+
// Find the max number and multiply it by 10 to get a number
3+
// with no. of digits of max + 1
4+
const maxNum = Math.max(...arr) * 10;
5+
let divisor = 10;
6+
while (divisor < maxNum) {
7+
// Create bucket arrays for each of 0-9
8+
let buckets = [...Array(10)].map(() => []);
9+
// For each number, get the current significant digit and put it in the respective bucket
10+
for (let num of arr) {
11+
buckets[Math.floor((num % divisor) / (divisor / 10))].push(num);
12+
}
13+
// Reconstruct the array by concatinating all sub arrays
14+
arr = [].concat.apply([], buckets);
15+
// Move to the next significant digit
16+
divisor *= 10;
17+
}
18+
return arr;
19+
}

0 commit comments

Comments
 (0)