text: Maximum in an array that can make another array sorted | Python3 program to make array sorted ; Function to check whether there is any swappable element present to make the first array sorted ; wrongIdx is the index of the element which is making the first array unsorted ; Find the maximum element which satisfies the above mentioned neighboring conditions ; if res is true then swap the element and make the first array sorted ; Function to print the sorted array if elements are swapped . ; Driver code
code: import sys NEW_LINE def swapElement ( arr1 , arr2 , n ) : NEW_LINE INDENT wrongIdx = 0 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr1 [ i ] < arr1 [ i - 1 ] ) : NEW_LINE INDENT wrongIdx = i NEW_LINE DEDENT DEDENT maximum = - ( sys . maxsize - 1 ) NEW_LINE maxIdx = - 1 NEW_LINE res = False NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr2 [ i ] > maximum and arr2 [ i ] >= arr1 [ wrongIdx - 1 ] ) : NEW_LINE INDENT if ( wrongIdx + 1 <= n - 1 and arr2 [ i ] <= arr1 [ wrongIdx + 1 ] ) : NEW_LINE INDENT maximum = arr2 [ i ] NEW_LINE maxIdx = i NEW_LINE res = True NEW_LINE DEDENT DEDENT DEDENT if ( res ) : NEW_LINE INDENT ( arr1 [ wrongIdx ] , arr2 [ maxIdx ] ) = ( arr2 [ maxIdx ] , arr1 [ wrongIdx ] ) NEW_LINE DEDENT return res NEW_LINE DEDENT def getSortedArray ( arr1 , arr2 , n ) : NEW_LINE INDENT if ( swapElement ( arr1 , arr2 , n ) ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr1 [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " Not ▁ Possible " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr1 = [ 1 , 3 , 7 , 4 , 10 ] NEW_LINE arr2 = [ 2 , 1 , 6 , 8 , 9 ] NEW_LINE n = len ( arr1 ) NEW_LINE getSortedArray ( arr1 , arr2 , n ) NEW_LINE DEDENT