text: Maximum in an array that can make another array sorted | Java 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: class GFG { static boolean swapElement ( int [ ] arr1 , int [ ] arr2 , int n ) { int wrongIdx = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr1 [ i ] < arr1 [ i - 1 ] ) { wrongIdx = i ; } } int maximum = Integer . MIN_VALUE ; int maxIdx = - 1 ; boolean res = false ; for ( int 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 ; } static void swap ( int [ ] a , int wrongIdx , int [ ] b , int maxIdx ) { int c = a [ wrongIdx ] ; a [ wrongIdx ] = b [ maxIdx ] ; b [ maxIdx ] = c ; } static void getSortedArray ( int arr1 [ ] , int arr2 [ ] , int n ) { if ( swapElement ( arr1 , arr2 , n ) ) { for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( arr1 [ i ] + " ▁ " ) ; } } else { System . out . println ( " Not ▁ Possible " ) ; } } public static void main ( String [ ] args ) { int arr1 [ ] = { 1 , 3 , 7 , 4 , 10 } ; int arr2 [ ] = { 2 , 1 , 6 , 8 , 9 } ; int n = arr1 . length ; getSortedArray ( arr1 , arr2 , n ) ; } }