Check if given array is almost sorted ( elements are at | CPP program to find whether given array 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 function
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool almostSort ( int A [ ] , int n ) { for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( A [ i ] > A [ i + 1 ] ) { swap ( A [ i ] , A [ i + 1 ] ) ; i ++ ; } } for ( int i = 0 ; i < n - 1 ; i ++ ) if ( A [ i ] > A [ i + 1 ] ) return false ; return true ; } int main ( ) { int A [ ] = { 1 , 3 , 2 , 4 , 6 , 5 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; if ( almostSort ( A , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }