Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 38ac557

Browse files
Add radix sort in JavaScript (Py-Contributors#912)
1 parent 4393ba8 commit 38ac557

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

‎Javascript/Algorithms/radix-sort.js‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
const unsortedArr = [31, 27, 28, 42, 13, 3, 50, 46, 25, 18, 33, 47, 4, 45, 39, 23, 2];
2+
3+
const getNum = (num, index) => {
4+
const strNum = String(num);
5+
let end = strNum.length - 1;
6+
const foundNum = strNum[end - index];
7+
8+
if (foundNum === undefined) return 0;
9+
else return foundNum;
10+
};
11+
12+
console.log(getNum(4353, 2));
13+
14+
const largestNum = arr => {
15+
let largest = "0";
16+
17+
arr.forEach(num => {
18+
const strNum = String(num);
19+
20+
if (strNum.length > largest.length) largest = strNum;
21+
});
22+
23+
return largest.length;
24+
};
25+
26+
const radixSort = arr => {
27+
let maxLength = largestNum(arr);
28+
29+
for (let i = 0; i < maxLength; i++) {
30+
let buckets = Array.from({ length: 10 }, () => []);
31+
32+
for (let j = 0; j < arr.length; j++) {
33+
let num = getNum(arr[j], i);
34+
35+
if (num !== undefined) buckets[num].push(arr[j]);
36+
};
37+
arr = buckets.flat();
38+
};
39+
return arr;
40+
};
41+
42+
console.log(radixSort(unsortedArr));

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /