text: Check if an array can be sorted by swapping pairs from indices consisting of unequal elements in another array | C ++ Program for 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
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkifSorted ( int A [ ] , int B [ ] , int N ) { bool 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 ; } int main ( ) { int A [ ] = { 3 , 1 , 2 } ; int B [ ] = { 0 , 1 , 1 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; bool check = checkifSorted ( A , B , N ) ; if ( check ) { cout << " YES " << endl ; } else { cout << " NO " << endl ; } return 0 ; }