-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgo-binarysearch
More file actions
33 lines (25 loc) · 810 Bytes
/
algo-binarysearch
File metadata and controls
33 lines (25 loc) · 810 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def binarySearch(array: list, target: int):
left = 0
right = len(array)
while left <= right:
mid = (left + right) // 2
if target == array[mid]:
return array.index(array[mid])
# return mid
elif target < array[mid]:
right = mid - 1
else:
left = mid + 1
else:
return -1
def binary_search(arr, target):
return binary_search_helper(arr, target, 0, len(arr) - 1)
def binary_search_helper(arr, target, left, right):
if left <= right:
mid = (left + right) // 2
if target == arr[mid]:
return mid
elif target < arr[mid]:
return binary_search_helper(arr, target, left, mid - 1)
else:
return binary_search_helper(arr, target, mid + 1, right)