MCPcopy Create free account
hub / github.com/geekcomputers/Python / binary_search

Function binary_search

Binary_search.py:3–21  ·  view source on GitHub ↗
(arr, l, r, x)

Source from the content-addressed store, hash-verified

1# It returns location of x in given array arr
2# if present, else returns -1
3def binary_search(arr, l, r, x):
4 # Base case: if left index is greater than right index, element is not present
5 if l > r:
6 return -1
7
8 # Calculate the mid index
9 mid = (l + r) // 2
10
11 # If element is present at the middle itself
12 if arr[mid] == x:
13 return mid
14
15 # If element is smaller than mid, then it can only be present in left subarray
16 elif arr[mid] > x:
17 return binary_search(arr, l, mid - 1, x)
18
19 # Else the element can only be present in right subarray
20 else:
21 return binary_search(arr, mid + 1, r, x)
22
23
24# Main Function

Callers 2

Binary_search.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected