Update binary_search.py

This commit is contained in:
marina 2023-08-07 21:47:06 -07:00 committed by GitHub
parent 8ef56f3b77
commit e372bbe6f7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -19,7 +19,7 @@ def binary_search_recursive(array, item, higher=None, lower=0):
return binary_search_recursive(array, item, mid - 1, lower)
else:
return binary_search_recursive(array, item, =higher, mid + 1)
return binary_search_recursive(array, item, higher, mid + 1)
def binary_search_iterative(array, item):
@ -29,7 +29,7 @@ def binary_search_iterative(array, item):
lower, higher = 0, len(array)
while lower <= higher:
while lower < higher:
mid = (higher + lower) // 2
if array[mid] == item:
@ -47,7 +47,7 @@ def binary_search_iterative(array, item):
def binary_search_matrix(matrix, item, lower=0, higher=None):
if not matrix:
return None
return False
rows = len(matrix)
cols = len(matrix[0])
@ -57,25 +57,12 @@ def binary_search_matrix(matrix, item, lower=0, higher=None):
mid = (higher + lower) // 2
row = mid // cols
col = mid % cols
item = matrix[row][col]
if item == item:
if item == matrix[row][col]:
return row, col
elif item < item:
elif item < matrix[row][col]:
return binary_search_matrix(matrix, item, lower, mid - 1)
else:
return binary_search_matrix(matrix, item, mid + 1, higher)
return None
if __name__ == '__main__':
array = [2, 3, 5, 6, 8, 10, 15, 23]
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
item = 15
print('Recursive: ', binary_search_recursive(array, item))
print('Iterative: ', binary_search_iterative(array, item))
print('Matrix: ', binary_search_matrix(matrix, item))
return False