Given two sorted integer arrays arr1 and arr2, merge arr1 and arr2 as one sorted array.
Example Input: arr1 = [1,2,3] arr2 = [2,5,6] Output: [1,2,2,3,5,6]
Solution1: we compare the corresponding elements of both arrays
We add the smaller element to a new array and increment the index of the array from which the element was added.
Again we compare the elements of both arrays and repeat the procedure until all the elements have been added.
#mergeSortedArrays([0,3,4,31], [3,4,6,30]);
def mergeSortedArrays(arr1, arr2):
new_arr = []
flag = 0
arr1_index = arr2_index = 0
while not (arr1_index >= len(arr1) or arr2_index >= len(arr2)):
if arr1[arr1_index] <= arr2[arr2_index]:
new_arr.append(arr1[arr1_index])
arr1_index += 1
else:
new_arr.append(arr2[arr2_index])
arr2_index += 1
if arr1_index == len(arr1):
flag = 1
if flag == 1:
for item in arr2[arr2_index:]:
new_arr.append(item)
else:
for item in arr1[arr1_index:]:
new_arr.append(item)
return new_arr
arr1 = [0,3,4,31]
arr2 = [3,4,6,30]
print(mergeSortedArrays(arr1, arr2))
#print(arr1 +arr2)
Output: [0, 3, 3, 4, 4, 6, 30, 31]
Solution2: we add both arrays and then use in build sort method to sort the array.
def mergesortedarr(a,b):
x=a+b
x.sort()
return x
a=[1,2,3,4]
b=[3,7,9,12]
qw=mergesortedarr(a,b)
print(qw)
output: [1, 2, 3, 3, 4, 7, 9, 12]