Skip to content

Commit 55bc5a7

Browse files
committed
Merge Sort added
1 parent 22d122f commit 55bc5a7

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Sorts/MergeSort.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
function Merge(left, right) {
2+
let resultArray = [], leftIndex = 0, rightIndex = 0;
3+
4+
while (leftIndex < left.length && rightIndex < right.length) {
5+
if (left[leftIndex] < right[rightIndex]) {
6+
resultArray.push(left[leftIndex]);
7+
leftIndex++;
8+
} else {
9+
resultArray.push(right[rightIndex]);
10+
rightIndex++;
11+
}
12+
}
13+
14+
return resultArray
15+
.concat(left.slice(leftIndex))
16+
.concat(right.slice(rightIndex));
17+
}
18+
19+
function MergeSort(arr) {
20+
if (arr.length <= 1) {
21+
return arr;
22+
}
23+
24+
let middle = Math.floor(arr.length/2);
25+
let left = arr.slice(0, middle);
26+
let right = arr.slice(middle);
27+
28+
return Merge(MergeSort(left), MergeSort(right));
29+
30+
}
31+
32+
export default MergeSort;

0 commit comments

Comments
 (0)