Skip to content

Commit cc2298f

Browse files
committed
updated
1 parent 6882a8b commit cc2298f

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
def merge(arr1: list[int], arr2: list[int]) -> list[int]:
2+
"""
3+
Merge two sorted arrays into a single sorted array.
4+
"""
5+
6+
i = j = 0
7+
result = []
8+
9+
while i < len(arr1) and j < len(arr2):
10+
11+
if (arr1[i] < arr2[j]):
12+
result.append(arr1[i])
13+
i += 1
14+
else:
15+
result.append(arr2[j])
16+
j += 1
17+
# one of the lists will reach the end first
18+
# so we need to add the remaining elements of the other list
19+
while i < len(arr1):
20+
result.append(arr1[i])
21+
i += 1
22+
while j < len(arr2):
23+
result.append(arr2[j])
24+
j += 1
25+
26+
return result
27+
28+
if __name__ == '__main__':
29+
arr1 = [1, 3, 5, 7]
30+
arr2 = [2, 4, 6, 8]
31+
print(merge(arr1, arr2)) # Output: [1, 2, 3, 4, 5, 6, 7, 8]
32+
arr1 = [1, 2, 3, 4]
33+
arr2 = [5, 6, 7, 8]
34+
print(merge(arr1, arr2)) # Output: [1, 2, 3, 4, 5, 6, 7, 8]
35+
arr1 = [1, 2, 3, 4]
36+
arr2 = [1, 2, 3, 4]
37+
print(merge(arr1, arr2)) # Output: [1, 1, 2, 2, 3, 3, 4, 4]
38+
arr1 = [1, 2, 3, 4]
39+
arr2 = [5, 6, 7, 8, 9]
40+
print(merge(arr1, arr2)) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
41+
arr1 = [5, 6, 7, 8, 9]
42+
arr2 = [1, 2, 3, 4]
43+
print(merge(arr1, arr2)) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
44+
arr1 = [1, 2, 3, 4]
45+
arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
46+
print(merge(arr1, arr2)) # Output: [1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9]

0 commit comments

Comments
 (0)