Check if it is possible to sort an array with conditional swapping of adjacent allowed | C ++ program to check if we can sort an array with adjacent swaps allowed ; Returns true if it is possible to sort else false / ; We need to do something only if previousl element is greater ; If difference is more than one , then not possible ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkForSorting ( int arr [ ] , int n ) { for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] > arr [ i + 1 ] ) { if ( arr [ i ] - arr [ i + 1 ] == 1 ) swap ( arr [ i ] , arr [ i + 1 ] ) ; else return false ; } } return true ; } int main ( ) { int arr [ ] = { 1 , 0 , 3 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( checkForSorting ( arr , n ) ) cout << " Yes " ; else cout << " No " ; }