Check if an array of pairs can be sorted by swapping pairs with different first elements | 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 ] [ 1 ] is not equal to that of the group ; If array is sorted ; Driver Code
def isSorted ( arr , N ) : NEW_LINE INDENT for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ i ] [ 0 ] > arr [ i - 1 ] [ 0 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isPossibleToSort ( arr , N ) : NEW_LINE INDENT group = arr [ 0 ] [ 1 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ i ] [ 1 ] != group ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT DEDENT if ( isSorted ( arr , N ) ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT else : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 340000 , 2 ] , [ 45000 , 1 ] , [ 30000 , 2 ] , [ 50000 , 4 ] ] NEW_LINE N = len ( arr ) NEW_LINE print ( isPossibleToSort ( arr , N ) ) NEW_LINE DEDENT