Maximum in an array that can make another 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
function swapElement ( arr1 , arr2 , n ) { let wrongIdx = 0 ; for ( let i = 1 ; i < n ; i ++ ) { if ( arr1 [ i ] < arr1 [ i - 1 ] ) { wrongIdx = i ; } } let maximum = Number . MIN_VALUE ; let maxIdx = - 1 ; let res = false ; for ( let i = 0 ; i < n ; i ++ ) { if ( arr2 [ i ] > maximum && arr2 [ i ] >= arr1 [ wrongIdx - 1 ] ) { if ( wrongIdx + 1 <= n - 1 && arr2 [ i ] <= arr1 [ wrongIdx + 1 ] ) { maximum = arr2 [ i ] ; maxIdx = i ; res = true ; } } } if ( res ) { swap ( arr1 , wrongIdx , arr2 , maxIdx ) ; } return res ; } function swap ( a , wrongIdx , b , maxIdx ) { let c = a [ wrongIdx ] ; a [ wrongIdx ] = b [ maxIdx ] ; b [ maxIdx ] = c ; } function getSortedArray ( arr1 , arr2 , n ) { if ( swapElement ( arr1 , arr2 , n ) ) { for ( let i = 0 ; i < n ; i ++ ) { document . write ( arr1 [ i ] + " " ) ; } } else { document . write ( " " ) ; } } let arr1 = [ 1 , 3 , 7 , 4 , 10 ] ; let arr2 = [ 2 , 1 , 6 , 8 , 9 ] ; let n = arr1 . length ; getSortedArray ( arr1 , arr2 , n ) ;