-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmergesort.js
73 lines (53 loc) · 1.24 KB
/
mergesort.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
65
66
67
68
69
70
71
72
"use strict";
/*Implement merge sort*/
function mergeSort(arr, start, end, result) {
start = start || 0;
end = end || arr.length;
result = result || [];
if(start == (end - 1)) {
result[start] = start;
return;
}
var mid = Math.floor( (start + end)/2 );
//sort left
mergeSort(arr, start, mid, result);
//sort right
mergeSort(arr, mid, end, result);
//merge the results
var leftHasValue = start < mid,
rightHasValue = mid < end,
leftVal,
rightVal;
for(var index1 = start, index2 = mid, resIndex = start; (leftHasValue || rightHasValue); resIndex++) {
if(leftHasValue) {
leftVal = arr[index1];
}
if(rightHasValue) {
rightVal = arr[index2];
}
if(leftHasValue && rightHasValue) {
if(leftVal <= rightVal) {
result[resIndex] = leftVal;
index1++;
}else {
result[resIndex] = rightVal;
index2++;
}
} else if(leftHasValue) {
result[resIndex] = leftVal;
index1++;
} else if(rightHasValue) {
result[resIndex] = rightVal;
index2++;
}
leftHasValue = index1 < mid;
rightHasValue = index2 < end;
}
copyArray(result, arr, start, end);
}
function copyArray(from, to, start, end) {
for(var i = start; i < end; i++) {
to[i] = from[i];
}
}
module.exports = mergeSort;