Update binary_search.py

This commit is contained in:
marina 2023-07-31 14:58:10 -07:00 committed by GitHub
parent afdff04a69
commit 2396654457
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -6,16 +6,20 @@
def binary_search_recursive(array, item, higher=None, lower=0):
higher = higher or len(array)
if higher < lower:
return False
mid = (higher + lower) // 2
if item == array[mid]:
return mid
elif item < array[mid]:
return binary_search_recursive(array, item, higher=mid-1, lower=lower)
return binary_search_recursive(array, item, mid - 1, lower)
else:
return binary_search_recursive(array, item, higher=higher, lower=mid+1)
return binary_search_recursive(array, item, =higher, mid + 1)
def binary_search_iterative(array, item):
@ -23,17 +27,20 @@ def binary_search_iterative(array, item):
while lower < higher:
mid = (highe r+ lower) // 2
if array[mid] == item:
return mid
elif array[mid] > item:
higher = mid
else:
lower = mid + 1
return False
def binary_search_matrix(matrix, item, lower=0, higher=None):
""" Binary search in a matrix """
if not matrix:
return None