Merge two sorted arrays | Merge arr1 [ 0. . n1 - 1 ] and arr2 [ 0. . n2 - 1 ] into arr3 [ 0. . n1 + n2 - 1 ] ; Traverse both array ; Check if current element of first array is smaller than current element of second array . If yes , store first array element and increment first array index . Otherwise do same with second array ; Store remaining elements of first array ; Store remaining elements of second array ; Driver code
def mergeArrays ( arr1 , arr2 , n1 , n2 ) : NEW_LINE INDENT arr3 = [ None ] * ( n1 + n2 ) NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE k = 0 NEW_LINE while i < n1 and j < n2 : NEW_LINE INDENT if arr1 [ i ] < arr2 [ j ] : NEW_LINE INDENT arr3 [ k ] = arr1 [ i ] NEW_LINE k = k + 1 NEW_LINE i = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT arr3 [ k ] = arr2 [ j ] NEW_LINE k = k + 1 NEW_LINE j = j + 1 NEW_LINE DEDENT DEDENT while i < n1 : NEW_LINE INDENT arr3 [ k ] = arr1 [ i ] ; NEW_LINE k = k + 1 NEW_LINE i = i + 1 NEW_LINE DEDENT while j < n2 : NEW_LINE INDENT arr3 [ k ] = arr2 [ j ] ; NEW_LINE k = k + 1 NEW_LINE j = j + 1 NEW_LINE DEDENT print ( " Array ▁ after ▁ merging " ) NEW_LINE for i in range ( n1 + n2 ) : NEW_LINE INDENT print ( str ( arr3 [ i ] ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr1 = [ 1 , 3 , 5 , 7 ] NEW_LINE n1 = len ( arr1 ) NEW_LINE arr2 = [ 2 , 4 , 6 , 8 ] NEW_LINE n2 = len ( arr2 ) NEW_LINE mergeArrays ( arr1 , arr2 , n1 , n2 ) ; NEW_LINE