Sort an array by swapping elements of different type specified by another array | Function to check if it is possible to sort the array in non - decreasing order by swapping elements of different types ; Consider the array to be already sorted ; Checking if array is already sorted ; Check for a pair which is in decreasing order ; Count the frequency of each type of element ; type0 stores count of elements of type 0 ; type1 stores count of elements of type 1 ; Return true if array is already sorted ; Return false if all elements are of same type and array is unsorted ; Possible for all other cases ; Driver code
def sorting_possible ( a , b , n ) : NEW_LINE INDENT sorted = True NEW_LINE type1 = 0 NEW_LINE type0 = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( a [ i ] < a [ i - 1 ] ) : NEW_LINE INDENT sorted = False NEW_LINE break NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( b [ i ] == 0 ) : NEW_LINE INDENT type0 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT type1 += 1 NEW_LINE DEDENT DEDENT if ( sorted != False ) : NEW_LINE INDENT return True NEW_LINE DEDENT elif ( type1 == n or type0 == n ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT a = [ 15 , 1 , 2 , 17 , 6 ] NEW_LINE b = [ 1 , 1 , 0 , 1 , 1 ] NEW_LINE n = len ( a ) NEW_LINE res = sorting_possible ( a , b , n ) NEW_LINE if ( res != False ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT