-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmergesort.js
52 lines (46 loc) · 1.18 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
function split(wholeArray) {
const midPoint = Math.floor(wholeArray.length / 2);
const firstHalf = wholeArray.slice(0, midPoint);
//console.log('this is firstHalf->', firstHalf);
const secondHalf = wholeArray.slice(midPoint);
//console.log('this is secondHalf->', secondHalf);
return [firstHalf, secondHalf];
}
function merge(left, right) {
const result = [];
let i = 0;
let j = 0;
while (left[i] && right[j]) {
if (left[i] < right[j]) {
result.push(left[i]);
i++;
} else if (right[j] <= left[i]) {
result.push(right[j]);
j++;
}
}
if (left[i]) {
for (let idx = i; idx < left.length; idx++) {
result.push(left[idx]);
}
} else if (right[j]) {
for (let num = j; num < right.length; num++) {
result.push(right[num]);
}
}
console.log('merge result', result);
return result;
}
function mergeSort(array) {
if (array.length < 2) {
return array;
}
debugger;
//const midPoint = Math.floor(end / 2);
//, start = 0, end = array.length
const splitArray = split(array);
const left = mergeSort(splitArray[0]);
const right = mergeSort(splitArray[1]);
const result = merge(left, right);
return result;
}