-
Notifications
You must be signed in to change notification settings - Fork 0
/
LSD_RadixSort_Javascript.js
64 lines (62 loc) · 1.82 KB
/
LSD_RadixSort_Javascript.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// LSD Radix Sort Implemented with Javascript
function Queue(){
this.dataStore = [];
this.enqueue = enqueue;
this.dequeue = dequeue;
this.isEmpty = isEmpty;
};
function enqueue(element){
this.dataStore.push(element);
};
function dequeue(){
if(this.dataStore.length == 0){
return false;
} else {
return this.dataStore.shift();
}
};
function isEmpty(){
if(this.dataStore.length == 0){
return true;
} else {
return false;
}
};
function radix(data){
var bin = [];
var digIndex = [];
for(var i = 0; i < 10; i++){
bin[i] = new Queue(); // create and store 10 instances of the Queue class in bin array
}; // Block 1------------------------------
for(var i = 0; i < data.length; i++){
bin[data[i]%10].enqueue(data[i]);
};
for(var i = 0; i < bin.length; i++){
digIndex.push(bin[i].dataStore.length);
};
for(var i = 0; i < digIndex.length - 1; i++){
digIndex[i + 1] += digIndex[i];
};
for(var i = bin.length - 1; i >= 0; i--){
while(!bin[i].isEmpty()){
data[--digIndex[i]] = bin[i].dequeue();
}
}; // Block 2------------------------------
digIndex = []; // re-initialize digIndex
for(var i = data.length - 1; i >= 0; i--){
bin[Math.floor(data[i]/10)%10].enqueue(data[i]);
};
for(var i = 0; i < bin.length; i++){
digIndex.push(bin[i].dataStore.length);
};
for(var i = 0; i < digIndex.length - 1; i++){
digIndex[i + 1] += digIndex[i];
};
for(var i = bin.length - 1; i >= 0; i--){
while(!bin[i].isEmpty()){
data[--digIndex[i]] = bin[i].dequeue();
}
};
return data;
};
// Code created and written by Anthony Poblacion