Skip to content

Commit 3da4523

Browse files
authored
Create merge-sort.js
1 parent 74c5bbf commit 3da4523

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

merge-sort.js

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
const merge = (arrayA, arrayB) => {
2+
let pointerA = 0,
3+
pointerB = 0,
4+
sortedArray = [];
5+
6+
while (pointerA < arrayA.length && pointerB < arrayB.length) {
7+
if (arrayA[pointerA] < arrayB[pointerB]) {
8+
sortedArray.push(arrayA[pointerA]);
9+
pointerA++;
10+
} else {
11+
sortedArray.push(arrayB[pointerB]);
12+
pointerB++;
13+
}
14+
}
15+
if (pointerA < arrayA.length) {
16+
sortedArray = sortedArray.concat(arrayA.slice(pointerA));
17+
}
18+
if (pointerB < arrayB.length) {
19+
sortedArray = sortedArray.concat(arrayB.slice(pointerB));
20+
}
21+
22+
return sortedArray;
23+
};
24+
25+
const mergeSort = array => {
26+
if (array.length <= 1) {
27+
return array;
28+
}
29+
30+
const left = array.slice(0, array.length / 2);
31+
const right = array.slice(array.length / 2);
32+
33+
const leftSorted = mergeSort(left);
34+
const rightSorted = mergeSort(right);
35+
36+
return merge(leftSorted, rightSorted);
37+
};
38+
39+
const array = [22, 18, -4, 58, 7, 31, 42];
40+
41+
const sortedArray = mergeSort(array);
42+
console.log(sortedArray);

0 commit comments

Comments
 (0)