Check if an array of pairs can be sorted by swapping pairs with different first elements | java 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
import java . io . * ; import java . lang . * ; import java . util . * ; public class GFG { static boolean isSorted ( int [ ] [ ] arr , int N ) { for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ i ] [ 0 ] > arr [ i - 1 ] [ 0 ] ) { return false ; } } return true ; } static String isPossibleToSort ( int [ ] [ ] arr , int N ) { int group = arr [ 0 ] [ 1 ] ; for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ i ] [ 1 ] != group ) { return " Yes " ; } } if ( isSorted ( arr , N ) ) { return " Yes " ; } else { return " No " ; } } public static void main ( String [ ] args ) { int arr [ ] [ ] = { { 340000 , 2 } , { 45000 , 1 } , { 30000 , 2 } , { 50000 , 4 } } ; int N = arr . length ; System . out . print ( isPossibleToSort ( arr , N ) ) ; } }