text: Check if an array of pairs can be sorted by swapping pairs with different first elements | C ++ program for the above approach ; Function to check if an array is sorted or not ; Traverse the array arr [ ] ; Return true ; Function to check if it is possible to sort the array w . r . t . first element ; Stores the ID of the first element ; Traverse the array arr [ ] ; If arr [ i ] . second is not equal to that of the group ; If array is sorted ; Driver Code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isSorted ( pair < int , int > * arr , int N ) { for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ i ] . first > arr [ i - 1 ] . first ) { return false ; } } return true ; } string isPossibleToSort ( pair < int , int > * arr , int N ) { int group = arr [ 0 ] . second ; for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ i ] . second != group ) { return " Yes " ; } } if ( isSorted ( arr , N ) ) { return " Yes " ; } else { return " No " ; } } int main ( ) { pair < int , int > arr [ ] = { { 340000 , 2 } , { 45000 , 1 } , { 30000 , 2 } , { 50000 , 4 } } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << isPossibleToSort ( arr , N ) ; return 0 ; }