Check if it is possible to sort an array with conditional swapping of adjacent allowed | Returns true if it is possible to sort else false ; We need to do something only if previousl element is greater ; If difference is more than one , then not possible ; Driver Code
< ? php function checkForSorting ( $ arr , $ n ) { $ temp = 0 ; for ( $ i = 0 ; $ i < $ n - 1 ; $ i ++ ) { if ( $ arr [ $ i ] > $ arr [ $ i + 1 ] ) { if ( $ arr [ $ i ] - $ arr [ $ i + 1 ] == 1 ) { $ temp = $ arr [ $ i ] ; $ arr [ $ i ] = $ arr [ $ i + 1 ] ; $ arr [ $ i + 1 ] = $ temp ; } else return false ; } } return true ; } $ arr = array ( 1 , 0 , 3 , 2 ) ; $ n = sizeof ( $ arr ) ; if ( checkForSorting ( $ arr , $ n ) ) echo " Yes " ; else echo " No " ; ? >