Check if reversing a sub array make the array sorted | Return true , if reversing the subarray will sort the array , else return false . ; Copying the array . ; Sort the copied array . ; Finding the first mismatch . ; Finding the last mismatch . ; If whole array is sorted ; Checking subarray is decreasing or not . ; Driver Code
function checkReverse ( arr , n ) { let temp = [ ] ; for ( let i = 0 ; i < n ; i ++ ) { temp [ i ] = arr [ i ] ; } temp . sort ( ) ; let front ; for ( front = 0 ; front < n ; front ++ ) { if ( temp [ front ] != arr [ front ] ) { break ; } } let back ; for ( back = n - 1 ; back >= 0 ; back -- ) { if ( temp [ back ] != arr [ back ] ) { break ; } } if ( front >= back ) { return true ; } do { front ++ ; if ( arr [ front - 1 ] < arr [ front ] ) { return false ; } } while ( front != back ) ; return true ; } let arr = [ 1 , 2 , 5 , 4 , 3 ] ; let n = arr . length ; if ( checkReverse ( arr , n ) ) { document . write ( " " ) ; } else { document . write ( " " ) ; }