Binary Search | It returns location of x in given array arr if present , else returns - 1 ; Check if x is present at mid ; If x is greater , ignore left half ; If x is smaller , ignore right half ; If we reach here , then the element was not present ; Driver Code
def binarySearch ( arr , l , r , x ) : NEW_LINE INDENT while l <= r : NEW_LINE INDENT mid = l + ( r - l ) // 2 ; NEW_LINE if arr [ mid ] == x : NEW_LINE INDENT return mid NEW_LINE DEDENT elif arr [ mid ] < x : NEW_LINE INDENT l = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT r = mid - 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 2 , 3 , 4 , 10 , 40 ] NEW_LINE x = 10 NEW_LINE result = binarySearch ( arr , 0 , len ( arr ) - 1 , x ) NEW_LINE if result != - 1 : NEW_LINE INDENT print ( " Element ▁ is ▁ present ▁ at ▁ index ▁ % ▁ d " % result ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Element ▁ is ▁ not ▁ present ▁ in ▁ array " ) NEW_LINE DEDENT