Binary Search | Returns index of x in arr if present , else - 1 ; If element is present at the middle itself ; If element is smaller than mid , then it can only be present in left subarray ; Else the element can only be present in right subarray ; Element is not present in the array ; Driver Code
def binarySearch ( arr , l , r , x ) : NEW_LINE INDENT if r >= l : 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 return binarySearch ( arr , l , mid - 1 , x ) NEW_LINE DEDENT else : NEW_LINE INDENT return binarySearch ( arr , mid + 1 , r , x ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT 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