Skip to content

Commit 06dd311

Browse files
committed
--update: code for 'merge 2 sorted arrays'
1 parent 9ee032b commit 06dd311

File tree

1 file changed

+40
-0
lines changed
  • src/_Problems_/merge-two-sorted-arrays

1 file changed

+40
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// the running complexity O(n + m) where n and m are the length of 2 arrays
2+
function mergeTwoSortedArrays(arr1, arr2) {
3+
let i = 0;
4+
let j = 0;
5+
6+
const merged = [];
7+
8+
while (i < arr1.length && j < arr2.length) {
9+
if (arr1[i] < arr2[j]) {
10+
merged.push(arr1[i]);
11+
i += 1;
12+
} else {
13+
merged.push(arr2[j]);
14+
j += 1;
15+
}
16+
}
17+
18+
// if still elments are left in arr1
19+
if (i < arr1.length) {
20+
while (i < arr1.length) {
21+
merged.push(arr1[i]);
22+
i += 1;
23+
}
24+
}
25+
26+
// if still elments are left in arr2
27+
if (j < arr2.length) {
28+
while (j < arr2.length) {
29+
merged.push(arr2[j]);
30+
j += 1;
31+
}
32+
}
33+
34+
return merged;
35+
}
36+
37+
// since we are using sort here, the running time complexity will be O(nlogn)
38+
function mergeTwoSortedArrays2(arr1, arr2) {
39+
return [...arr1, ...arr2].sort((a, b) => a - b);
40+
}

0 commit comments

Comments
 (0)