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 4f2361c

Browse files
authored
Merge pull request #26 from Panzki/radixSort
Added radixsort algorithm.
2 parents 41705e6 + a7a192a commit 4f2361c

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

‎Sorts/radixSort.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
* Radix sorts an integer array without comparing the integers.
3+
* It groups the integers by their digits which share the same
4+
* significant position.
5+
* For more information see: https://en.wikipedia.org/wiki/Radix_sort
6+
*/
7+
function radixSort(items, RADIX) {
8+
9+
//default radix is then because we usually count to base 10
10+
if (RADIX === undefined || RADIX < 1) {
11+
RADIX = 10;
12+
}
13+
14+
var maxLength = false;
15+
var placement = 1;
16+
17+
while (!maxLength) {
18+
maxLength = true;
19+
var buckets = [];
20+
21+
for (var i = 0; i < RADIX; i++) {
22+
buckets.push([]);
23+
}
24+
25+
for (var j = 0; j < items.length; j++) {
26+
var tmp = items[j] / placement;
27+
buckets[Math.floor(tmp % RADIX)].push(items[j]);
28+
if (maxLength && tmp > 0) {
29+
maxLength = false;
30+
}
31+
}
32+
33+
var a = 0;
34+
for (var b = 0; b < RADIX; b++) {
35+
var buck = buckets[b];
36+
for (var k = 0; k < buck.length; k++) {
37+
items[a] = buck[k];
38+
a++;
39+
}
40+
}
41+
placement *= RADIX;
42+
}
43+
return items;
44+
}
45+
46+
//Implementation of radixSort
47+
48+
var ar = [5, 6, 7, 8, 1, 2, 12, 14];
49+
//Array before Sort
50+
console.log(ar);
51+
radixSort(ar);
52+
//Array after sort
53+
console.log(ar);

0 commit comments

Comments
(0)

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