Check if reversing a sub array make the array sorted | Java program to check whether reversing a sub array make the array sorted or not ; 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 . ; Driven Program
import java . util . Arrays ; class GFG { static boolean checkReverse ( int arr [ ] , int n ) { int temp [ ] = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { temp [ i ] = arr [ i ] ; } Arrays . sort ( temp ) ; int front ; for ( front = 0 ; front < n ; front ++ ) { if ( temp [ front ] != arr [ front ] ) { break ; } } int 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 ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 5 , 4 , 3 } ; int n = arr . length ; if ( checkReverse ( arr , n ) ) { System . out . print ( " Yes " ) ; } else { System . out . print ( " No " ) ; } } }