Merging two unsorted arrays in sorted order | Function to merge array in sorted order ; Sorting a [ ] and b [ ] ; Merge two sorted arrays into res [ ] ; Merging remaining elements of a [ ] ( if any ) ; Merging remaining elements of b [ ] ( if any ) ; Driver code ; Final merge list
def sortedMerge ( a , b , res , n , m ) : NEW_LINE INDENT a . sort ( ) NEW_LINE b . sort ( ) NEW_LINE i , j , k = 0 , 0 , 0 NEW_LINE while ( i < n and j < m ) : NEW_LINE INDENT if ( a [ i ] <= b [ j ] ) : NEW_LINE INDENT res [ k ] = a [ i ] NEW_LINE i += 1 NEW_LINE k += 1 NEW_LINE DEDENT else : NEW_LINE INDENT res [ k ] = b [ j ] NEW_LINE j += 1 NEW_LINE k += 1 NEW_LINE DEDENT DEDENT while ( i < n ) : NEW_LINE INDENT res [ k ] = a [ i ] NEW_LINE i += 1 NEW_LINE k += 1 NEW_LINE DEDENT while ( j < m ) : NEW_LINE INDENT res [ k ] = b [ j ] NEW_LINE j += 1 NEW_LINE k += 1 NEW_LINE DEDENT DEDENT a = [ 10 , 5 , 15 ] NEW_LINE b = [ 20 , 3 , 2 , 12 ] NEW_LINE n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE res = [ 0 for i in range ( n + m ) ] NEW_LINE sortedMerge ( a , b , res , n , m ) NEW_LINE print " Sorted ▁ merged ▁ list ▁ : " NEW_LINE for i in range ( n + m ) : NEW_LINE INDENT print res [ i ] , NEW_LINE DEDENT