-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergesort.js
45 lines (38 loc) · 976 Bytes
/
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
function split(wholeArray) {
let halfIndex = Math.ceil(wholeArray.length / 2);
let firstHalf = wholeArray.slice(0, halfIndex);
let secondHalf = wholeArray.slice(halfIndex)
return [firstHalf, secondHalf];
}
//
function merge(leftArr, rightArr) {
let sorted = [];
let left = 0;
let right = 0;
while (left < leftArr.length && right < rightArr.length) {
if (leftArr[left] < rightArr[right]) {
sorted.push(leftArr[left++])
}
else {
sorted.push(rightArr[right++])
}
}
for (; left < leftArr.length; left++) {
sorted.push(leftArr[left])
}
for (; right < rightArr.length; right++) {
sorted.push(rightArr[right])
}
return sorted;
}
function mergeSort(array) {
let splited = split(array);
if (splited.length === 1) {
return array;
}
if (splited.length === 2) {
return merge(array[0], array[1]);
}
else {
}
}