text: Maximum in an array that can make another array sorted | C ++ 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 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 . ; Drivers code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; bool 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 = INT_MIN ; int maxIdx = -1 ; bool 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 ; } void getSortedArray ( int arr1 [ ] , int arr2 [ ] , int n ) { if ( swapElement ( arr1 , arr2 , n ) ) for ( int i = 0 ; i < n ; i ++ ) cout << arr1 [ i ] << " ▁ " ; else cout << " Not ▁ Possible " << endl ; } int main ( ) { int arr1 [ ] = { 1 , 3 , 7 , 4 , 10 } ; int arr2 [ ] = { 2 , 1 , 6 , 8 , 9 } ; int n = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; getSortedArray ( arr1 , arr2 , n ) ; }