-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmergeSort.js
56 lines (42 loc) · 1.27 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
function mergeSort(array) {
// Excluded cases
if(!Array.isArray(array) || isNaN(array[0])) return 'Please pass in an array of numbers';
// Base case
if(array.length === 1) return array;
// If array is bigger than 1, cut it in two
const pivot = Math.floor(array.length / 2);
let left = array.slice(0, pivot);
let right = array.slice(pivot, array.length);
// Step 1: Sort the left side array
left = mergeSort(left);
// Step 2: Sort the right side array
right = mergeSort(right);
// Step 3: Merge
return merge(left, right);
}
function merge(left, right) {
const merged = [];
while (left.length > 0 && right.length > 0) {
if (left[0] < right[0]) {
// add left to the merged array
merged.push(left[0]);
// remove left[0] from left
left.shift();
} else {
// add right to the merged array
merged.push(right[0]);
// remove right[0] from right
right.shift();
}
}
while (right.length > 0) {
merged.push(right[0]);
right.shift();
}
while (left.length > 0) {
merged.push(left[0]);
left.shift();
}
return merged;
}
module.exports = mergeSort;