Sorting array with conditional swapping | CPP program to Check if it is possible to sort the array in ascending order . ; Function to check if it is possible to sort the array ; Calculating max_element at each iteration . ; if we can not swap the i - th element . ; if it is impossible to swap the max_element then we can not sort the array . ; Otherwise , we can sort the array . ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; string possibleToSort ( int * arr , int n , string str ) { int max_element = -1 ; for ( long i = 0 ; i < str . size ( ) ; i ++ ) { max_element = max ( max_element , arr [ i ] ) ; if ( str [ i ] == '0' ) { if ( max_element > i + 1 ) return " No " ; } } return " Yes " ; } int main ( ) { int arr [ ] = { 1 , 2 , 5 , 3 , 4 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; string str = "01110" ; cout << possibleToSort ( arr , n , str ) ; return 0 ; }