-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmerge-sort.js
42 lines (34 loc) · 987 Bytes
/
merge-sort.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
const merge = (arrayA, arrayB) => {
let pointerA = 0,
pointerB = 0,
sortedArray = [];
while (pointerA < arrayA.length && pointerB < arrayB.length) {
if (arrayA[pointerA] < arrayB[pointerB]) {
sortedArray.push(arrayA[pointerA]);
pointerA++;
} else {
sortedArray.push(arrayB[pointerB]);
pointerB++;
}
}
if (pointerA < arrayA.length) {
sortedArray = sortedArray.concat(arrayA.slice(pointerA));
}
if (pointerB < arrayB.length) {
sortedArray = sortedArray.concat(arrayB.slice(pointerB));
}
return sortedArray;
};
const mergeSort = array => {
if (array.length <= 1) {
return array;
}
const left = array.slice(0, array.length / 2);
const right = array.slice(array.length / 2);
const leftSorted = mergeSort(left);
const rightSorted = mergeSort(right);
return merge(leftSorted, rightSorted);
};
const array = [22, 18, -4, 58, 7, 31, 42];
const sortedArray = mergeSort(array);
console.log(sortedArray);