Sorting array with conditional swapping | 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 . ; Driver Code
< ? php function possibleToSort ( $ arr , $ n , $ str ) { $ max_element = -1 ; for ( $ i = 0 ; $ i < sizeof ( $ str ) ; $ i ++ ) { $ max_element = max ( $ max_element , $ arr [ $ i ] ) ; if ( $ str [ $ i ] == '0' ) { if ( $ max_element > $ i + 1 ) return " No " ; } } return " Yes " ; } $ arr = array ( 1 , 2 , 5 , 3 , 4 , 6 ) ; $ n = sizeof ( $ arr ) ; $ str = "01110" ; echo possibleToSort ( $ arr , $ n , $ str ) ; ? >