Check if an array can be sorted by swapping pairs from indices consisting of unequal elements in another array | Java program of the above approach ; Function to check if array , A [ ] can be converted into sorted array by swapping ( A [ i ] , A [ j ] ) if B [ i ] not equal to B [ j ] ; Stores if array A [ ] is sorted in descending order or not ; Traverse the array A [ ] ; If A [ i ] is greater than A [ i + 1 ] ; Update flag ; If array is sorted in ascending order ; count = 2 : Check if 0 s and 1 s both present in the B [ ] ; Traverse the array ; If current element is 0 ; Update count ; Traverse the array B [ ] ; If current element is 1 ; If both 0 s and 1 s are present in the array ; Driver Code ; Input array A [ ] ; Input array B [ ] ; Function call ; If true , print YES ; Else print NO
import java . io . * ; class GFG { static boolean checkifSorted ( int A [ ] , int B [ ] , int N ) { boolean flag = false ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( A [ i ] > A [ i + 1 ] ) { flag = true ; break ; } } if ( ! flag ) { return true ; } int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( B [ i ] == 0 ) { count ++ ; break ; } } for ( int i = 0 ; i < N ; i ++ ) { if ( B [ i ] == 1 ) { count ++ ; break ; } } if ( count == 2 ) { return true ; } return false ; } public static void main ( String [ ] args ) { int A [ ] = { 3 , 1 , 2 } ; int B [ ] = { 0 , 1 , 1 } ; int N = A . length ; boolean check = checkifSorted ( A , B , N ) ; if ( check ) { System . out . println ( " YES " ) ; } else { System . out . println ( " NO " ) ; } } }