Merge an array of size n into another array of size m + n | Python program to Merge an array of size n into another array of size m + n ; Function to move m elements at the end of array mPlusN [ ] ; Merges array N [ ] of size n into array mPlusN [ ] of size m + n ; Current index of i / p part of mPlusN [ ] ; Current index of N [ ] ; Current index of output mPlusN [ ] ; Take an element from mPlusN [ ] if a ) value of the picked element is smaller and we have not reached end of it b ) We have reached end of N [ ] ; Otherwise take element from N [ ] ; Utility that prints out an array on a line ; Initialize arrays ; Move the m elements at the end of mPlusN ; Merge N [ ] into mPlusN [ ] ; Print the resultant mPlusN
NA = - 1 NEW_LINE def moveToEnd ( mPlusN , size ) : NEW_LINE INDENT i = 0 NEW_LINE j = size - 1 NEW_LINE for i in range ( size - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( mPlusN [ i ] != NA ) : NEW_LINE INDENT mPlusN [ j ] = mPlusN [ i ] NEW_LINE j -= 1 NEW_LINE DEDENT DEDENT DEDENT def merge ( mPlusN , N , m , n ) : NEW_LINE INDENT i = n NEW_LINE j = 0 NEW_LINE k = 0 NEW_LINE while ( k < ( m + n ) ) : NEW_LINE INDENT if ( ( j == n ) or ( i < ( m + n ) and mPlusN [ i ] <= N [ j ] ) ) : NEW_LINE INDENT mPlusN [ k ] = mPlusN [ i ] NEW_LINE k += 1 NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mPlusN [ k ] = N [ j ] NEW_LINE k += 1 NEW_LINE j += 1 NEW_LINE DEDENT DEDENT DEDENT def printArray ( arr , size ) : NEW_LINE INDENT for i in range ( size ) : NEW_LINE INDENT print ( arr [ i ] , " ▁ " , end = " " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT mPlusN = [ 2 , 8 , NA , NA , NA , 13 , NA , 15 , 20 ] NEW_LINE N = [ 5 , 7 , 9 , 25 ] NEW_LINE n = len ( N ) NEW_LINE m = len ( mPlusN ) - n NEW_LINE moveToEnd ( mPlusN , m + n ) NEW_LINE merge ( mPlusN , N , m , n ) NEW_LINE printArray ( mPlusN , m + n ) NEW_LINE