-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergeSort.js
39 lines (34 loc) · 1.03 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
const mergeSort = arr => {
const merge = (left, right) => {
let temp = [];
let leftIndex = 0;
let rightIndex = 0;
//initilizaing
for (let i = 0; ; i++) {
//specify stop condition
if (leftIndex === left.length) {
temp.push(...right.slice(rightIndex));
return temp;
}
if (rightIndex === right.length) {
temp.push(...left.slice(leftIndex));
return temp;
}
//---
//push the smaller number to temp and increment corresponding index
if (left[leftIndex] <= right[rightIndex]) {
temp.push(left[leftIndex]);
leftIndex++;
} else {
temp.push(right[rightIndex]);
rightIndex++;
}
}
};
//recurssively break original array to the point where all elements has only 1 item
if (arr.length === 1) return arr;
let left = mergeSort(arr.slice(0, Math.floor(arr.length / 2)));
let right = mergeSort(arr.slice(Math.floor(arr.length / 2), arr.length));
//merge two arrays back
return merge(left, right);
};