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
function almostSort ( A , n ) { for ( let i = 0 ; i < n - 1 ; i ++ ) { if ( A [ i ] > A [ i + 1 ] ) { let temp = A [ i ] ; A [ i ] = A [ i + 1 ] ; A [ i + 1 ] = temp ; i ++ ; } } for ( let i = 0 ; i < n - 1 ; i ++ ) if ( A [ i ] > A [ i + 1 ] ) return false ; return true ; } let A = [ 1 , 3 , 2 , 4 , 6 , 5 ] ; let n = A . length ; if ( almostSort ( A , n ) ) document . write ( " " ) ; else document . write ( " " ) ;