Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions searches/binary_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,25 @@
return last_result


# binary search uses divide and conquer
# We will leverage the fact that our list is sorted
def binary_search2(l, target, low=None, high=None):

Check failure on line 327 in searches/binary_search.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E741)

searches/binary_search.py:327:20: E741 Ambiguous variable name: `l`
if low is None:
low = 0
if high is None:
high = len(l) - 1
if high < low:
return -1

midpoint = (low + high) // 2
if l[midpoint] == target:
return midpoint
elif target < l[midpoint]:
return binary_search(l, target, low, midpoint - 1)
else:
return binary_search(l, target, midpoint + 1, high)


searches = ( # Fastest to slowest...
binary_search_std_lib,
binary_search,
Expand Down Expand Up @@ -358,3 +377,7 @@
print(f"{target} was not found in {collection}.")
else:
print(f"{target} was found at position {result} of {collection}.")

# Testing the binary search 2
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(binary_search(mylist, 10))
Loading