forked from akshitagit/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.js
More file actions
32 lines (25 loc) · 773 Bytes
/
MergeSort.js
File metadata and controls
32 lines (25 loc) · 773 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
function Merge(left, right) {
let resultArray = [], leftIndex = 0, rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
resultArray.push(left[leftIndex]);
leftIndex++;
} else {
resultArray.push(right[rightIndex]);
rightIndex++;
}
}
return resultArray
.concat(left.slice(leftIndex))
.concat(right.slice(rightIndex));
}
function MergeSort(arr) {
if (arr.length <= 1) {
return arr;
}
let middle = Math.floor(arr.length/2);
let left = arr.slice(0, middle);
let right = arr.slice(middle);
return Merge(MergeSort(left), MergeSort(right));
}
export default MergeSort;