Check if given array is almost sorted ( elements are at | JAVA Code to check if given array is almost sorted or not ; function for checking almost sort ; One by one compare adjacents . ; check whether resultant is sorted or not ; is resultant is sorted return true ; Driver program to test above function
import java . util . * ; class GFG { public static boolean almostSort ( int A [ ] , int n ) { for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( A [ i ] > A [ i + 1 ] ) { int temp = A [ i ] ; A [ i ] = A [ i + 1 ] ; A [ i + 1 ] = temp ; i ++ ; } } for ( int i = 0 ; i < n - 1 ; i ++ ) if ( A [ i ] > A [ i + 1 ] ) return false ; return true ; } public static void main ( String [ ] args ) { int A [ ] = { 1 , 3 , 2 , 4 , 6 , 5 } ; int n = A . length ; if ( almostSort ( A , n ) ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } }