Skip to content
Open

DONE #49

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
30 changes: 30 additions & 0 deletions search.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,33 @@
Output: 0
Explanation: -1 exists in the list and its index is 0
"""
# distance = high index -low index
# middle index = low index + (distance / 2)
# // mean forced integer division, meaning the retruns a full number and it rounds down, Ex. 2 // 5 = 2. ^^ this is used for odd index equations.

def binary_search(nums, target):
# keep track of the window -- start by assuming the entire list is the window
# var for the low index of the window, high index of the window, middle point index of the window
low = 0
high = len(nums)
mid = high // 2

# continously iterate until the target is found or we determine that the terget cannot be found
while True:
# check the value at the midpoint against the target, stop iterating if target is found
if nums[mid] == target:
return mid
# if the the value at the midpoint is less than the target, slide the window left
elif nums[mid] > target:
high = mid
diffrance = high - low
mid = low + (diffrance // 2)
else:
low = mid
diffrance = high - low
mid = low + (diffrance // 2)

# print (f'low: {low}, mid: {mid}, high: {high}')
# stop iteration when the midpoint is equal to low or high, because we didnt find it
if mid <= low or mid >= high:
return -1