fix broken case in binary search (python) and remove unneeded base cases
This commit is contained in:
@@ -1,15 +1,18 @@
|
|||||||
def binary_search(arr, target):
|
def binary_search(arr, target):
|
||||||
if not arr:
|
if not arr:
|
||||||
return -1
|
|
||||||
if len(arr) == 1 and arr[0] == target:
|
|
||||||
return arr[0]
|
|
||||||
if len(arr) == 1 and arr[0] != target:
|
|
||||||
return -1
|
return -1
|
||||||
low = 0
|
|
||||||
high = len(arr) - 1
|
low = 0
|
||||||
|
high = len(arr) - 1
|
||||||
mid = (low + high) // 2
|
mid = (low + high) // 2
|
||||||
|
|
||||||
if arr[mid] > target:
|
if arr[mid] == target:
|
||||||
|
return target
|
||||||
|
elif arr[mid] > target:
|
||||||
return binary_search(arr[:mid], target)
|
return binary_search(arr[:mid], target)
|
||||||
else:
|
else:
|
||||||
return binary_search(arr[mid+1:], target)
|
return binary_search(arr[mid+1:], target)
|
||||||
|
|
||||||
|
|
||||||
|
print(binary_search([6, 7, 8, 9, 10], 8))
|
||||||
|
print(binary_search([6, 7, 8, 9, 10], 6))
|
||||||
|
|||||||
Reference in New Issue
Block a user