-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.js
More file actions
47 lines (33 loc) · 924 Bytes
/
MergeSort.js
File metadata and controls
47 lines (33 loc) · 924 Bytes
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
function MergeSort(array){
this.Array=array;
}
MergeSort.prototype.Init = function() {
//
if (this.Array.length < 2)
return this.Array;
var split = parseInt(this.Array.length / 2);
var one = this.Array.slice(0, split);
var two = this.Array.slice(split, this.Array.length);
return this.Merge(new MergeSort(one).Init(),new MergeSort(two).Init() );
//
};
MergeSort.prototype.GetArray = function() {
return this.Init();
};
MergeSort.prototype.Merge = function(partOne,partTwo) {
var result = [];
while (partOne.length && partTwo.length) {
if (partOne[0] <= partTwo[0]) {
result.push(partOne.shift());
} else {
result.push(partTwo.shift());
}
}
while (partOne.length){
result.push(partOne.shift());
}
while (partTwo.length){
result.push(partTwo.shift());
}
return result;
};