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 b92ccc3

Browse files
authored
Create radix-sort.js
1 parent fe4299d commit b92ccc3

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

‎radix-sort.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
const getNthDigit = (number, n) => {
2+
for (let i = 0; i < n; i++) {
3+
number = Math.floor(number / 10);
4+
}
5+
return number % 10;
6+
};
7+
8+
const shouldStop = (array, dictionary) => {
9+
return dictionary.hasOwnProperty(0) && array.length === dictionary[0].length;
10+
};
11+
12+
const extractElements = dictionary => {
13+
return Object.keys(dictionary).reduce((elements, key) => {
14+
return dictionary[key] ? elements.concat(dictionary[key]) : elements;
15+
}, []);
16+
};
17+
18+
const radixSort = array => {
19+
let index = 0;
20+
while (true) {
21+
const dictionary = array.reduce((dict, element) => {
22+
const digit = getNthDigit(element, index);
23+
const elements = dict[digit] || [];
24+
dict[digit] = elements.concat(element);
25+
return dict;
26+
}, {});
27+
const extractedElements = extractElements(dictionary);
28+
array.length = 0;
29+
array.push(...extractedElements);
30+
if (shouldStop(array, dictionary)) {
31+
break;
32+
}
33+
index++;
34+
}
35+
};
36+
37+
const array = [10, 21, 17, 34, 44, 11, 654, 123];
38+
radixSort(array);
39+
console.log(array);

0 commit comments

Comments
(0)

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