Sort 1 to N by swapping adjacent elements | CPP program to test whether array can be sorted by swapping adjacent elements using boolean array ; Return true if array can be sorted otherwise false ; Check if array is sorted or not ; Driver program to test sortedAfterSwap ( )
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool sortedAfterSwap ( int A [ ] , bool B [ ] , int n ) { for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( B [ i ] ) { if ( A [ i ] != i + 1 ) swap ( A [ i ] , A [ i + 1 ] ) ; } } for ( int i = 0 ; i < n ; i ++ ) { if ( A [ i ] != i + 1 ) return false ; } return true ; } int main ( ) { int A [ ] = { 1 , 2 , 5 , 3 , 4 , 6 } ; bool B [ ] = { 0 , 1 , 1 , 1 , 0 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; if ( sortedAfterSwap ( A , B , n ) ) cout << " A ▁ can ▁ be ▁ sorted STRNEWLINE " ; else cout << " A ▁ can ▁ not ▁ be ▁ sorted STRNEWLINE " ; return 0 ; }