-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmergeSort.js
More file actions
36 lines (29 loc) · 1.04 KB
/
mergeSort.js
File metadata and controls
36 lines (29 loc) · 1.04 KB
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
// Divide and Conqure
// Time Complexity - O(n log(n))
// Space Complexity - O(n)
function merge(left, right) {
let arr = []
// let i = 0, j = 0;
// Break out of loop if any one of the array gets empty
while (left.length && right.length) {
// Pick the smaller among the smallest element of left and right sub arrays
if (left[0] < right[0]) {
arr.push(left.shift()) // Here will be O(n) we can say - arr.push(left[i++]);
} else {
arr.push(right.shift()) // Here will be O(n) we can say - arr.push(right[j++]);
}
}
// Concatenating the leftover elements
// (in case we didn't go through the entire left or right array)
return [ ...arr, ...left, ...right ]
}
const mergeSort = (array) => {
const half = array.length / 2
// Base case or terminating case
if(array.length < 2){
return array
}
const left = array.splice(0, half);
return merge(mergeSort(left),mergeSort(array))
};
console.log(mergeSort([2, 5, 3, 0, 57, 9, 12, 13]));