Print all the pairs that contains the positive and negative values of an element | Utility binary search ; Function ; Sort the array ; Traverse the array ; For every arr [ i ] < 0 element , do a binary search for arr [ i ] > 0. ; If found , print the pair . ; Driver code
def binary_search ( a , x , lo = 0 , hi = None ) : NEW_LINE INDENT if hi is None : NEW_LINE INDENT hi = len ( a ) NEW_LINE DEDENT while lo < hi : NEW_LINE INDENT mid = ( lo + hi ) // 2 NEW_LINE midval = a [ mid ] NEW_LINE if midval < x : NEW_LINE INDENT lo = mid + 1 NEW_LINE DEDENT elif midval > x : NEW_LINE INDENT hi = mid NEW_LINE DEDENT else : NEW_LINE INDENT return mid NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def printPairs ( arr , n ) : NEW_LINE INDENT pair_exists = Fals NEW_LINE arr . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT if ( binary_search ( arr , - arr [ i ] ) ) : NEW_LINE INDENT print ( arr [ i ] , " , ▁ " , - arr [ i ] ) NEW_LINE pair_exists = True NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( pair_exists == False ) : NEW_LINE INDENT print ( " No ▁ such ▁ pair ▁ exists " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 8 , 9 , - 4 , 1 , - 1 , - 8 , - 9 ] NEW_LINE n = len ( arr ) NEW_LINE printPairs ( arr , n ) NEW_LINE DEDENT