Check if the array can be sorted only if the elements on given positions can be swapped | Function to check if the array can be sorted only if the elements on the given positions can be swapped ; Creating an array for marking the positions ; Iterating through the array and mark the positions ; Iterating through the given array ; If pos [ i ] is 1 , then incrementing till 1 is continuously present in pos ; Sorting the required segment ; Checking if the vector is sorted or not ; Print yes if it is sorted ; Driver code
def check_vector ( A , n , p ) : NEW_LINE INDENT pos = [ 0 for i in range ( len ( A ) ) ] NEW_LINE for i in range ( len ( p ) ) : NEW_LINE INDENT pos [ p [ i ] - 1 ] = 1 NEW_LINE DEDENT flag = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( pos [ i ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT j = i NEW_LINE while ( j < n and pos [ j ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT p = A [ : i ] NEW_LINE q = A [ i : i + j + 1 ] NEW_LINE r = A [ i + j + 1 : len ( A ) ] NEW_LINE q . sort ( reverse = False ) NEW_LINE A = p + q + r NEW_LINE i = j NEW_LINE DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT if ( A [ i ] > A [ i + 1 ] ) : NEW_LINE INDENT flag = 0 NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag == 1 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 3 , 2 , 1 ] NEW_LINE p = [ 1 , 2 ] NEW_LINE check_vector ( A , len ( A ) , p ) NEW_LINE DEDENT