Check if given array is almost sorted ( elements are at | function for checking almost sort ; One by one compare adjacents . ; check whether resultant is sorted or not ; is resultant is sorted return true ; Driver Code
< ? php function almostSort ( $ A , $ n ) { for ( $ i = 0 ; $ i < $ n - 1 ; $ i ++ ) { if ( $ A [ $ i ] > $ A [ $ i + 1 ] ) { list ( $ A [ $ i ] , $ A [ $ i + 1 ] ) = array ( $ A [ $ i + 1 ] , $ A [ $ i ] ) ; $ i ++ ; } } for ( $ i = 0 ; $ i < $ n - 1 ; $ i ++ ) if ( $ A [ $ i ] > $ A [ $ i + 1 ] ) return false ; return true ; } $ A = array ( 1 , 3 , 2 , 4 , 6 , 5 ) ; $ n = sizeof ( $ A ) ; if ( almostSort ( $ A , $ n ) ) echo " Yes " , " STRNEWLINE " ; else echo " Yes " , " STRNEWLINE " ; ? >