Skip to content

Commit 428edfb

Browse files
committed
Implement merge method for merge sort
1 parent 376f1af commit 428edfb

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

Sorting/MergeSort.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
function merge(arr1, arr2, comparator) {
2+
if (typeof comparator !== "function") {
3+
comparator = (a, b) => a - b;
4+
}
5+
6+
const result = [];
7+
let p1 = 0,
8+
p2 = 0;
9+
10+
while (p1 < arr1.length && p2 < arr2.length) {
11+
if (comparator(arr1[p1], arr2[p2]) < 0) {
12+
result.push(arr1[p1]);
13+
p1++;
14+
} else {
15+
result.push(arr2[p2]);
16+
p2++;
17+
}
18+
}
19+
return result.concat(arr1.slice(p1), arr2.slice(p2));
20+
}
21+
22+
merge([1, 3, 6, 7], [2, 4, 6]);

0 commit comments

Comments
 (0)