Sorting array with conditional swapping | Java program to Check if it is possible to sort the array in ascending order . ; Function to check if it is possible to sort the array ; Calculating max_element at each iteration . ; if we can not swap the i - th element . ; if it is impossible to swap the max_element then we can not sort the array . ; Otherwise , we can sort the array . ; Driven Program
import java . util . * ; import java . lang . * ; class GFG { public static String possibleToSort ( int arr [ ] , int n , String str ) { int max_element = - 1 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { max_element = Math . max ( max_element , arr [ i ] ) ; if ( str . charAt ( i ) == '0' ) { if ( max_element > i + 1 ) return " No " ; } } return " Yes " ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 5 , 3 , 4 , 6 } ; int n = arr . length ; String str = "01110" ; System . out . println ( possibleToSort ( arr , n , str ) ) ; } }