From 58eb7349da94765e8e498efec4988a5e30e7dbe0 Mon Sep 17 00:00:00 2001 From: gloreea Date: Mon, 15 May 2023 09:59:32 -0700 Subject: [PATCH] deliverable complete w review notes --- search.py | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/search.py b/search.py index 1c03df0..51d4a0a 100644 --- a/search.py +++ b/search.py @@ -19,3 +19,53 @@ Output: 0 Explanation: -1 exists in the list and its index is 0 """ + + +# distance = high index - low index +# middle index = low index + (distance // 2) + +def binary_search(nums, target): + # keep track of the window -- start by assuming the entire list is the window + # vars for low index of the window, high index of the window, middle point index of the window + low = 0 + high = len(nums) + mid = high // 2 + + # account for case where target is first in the list + if target == nums[0]: + return 0 + # continously iterate until the target is found or we determine that the target 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 + elif nums[mid] > target: + high = mid + difference = high - low + mid = low + (difference // 2) + # otherwise slide to the right + else: + low = mid + difference = high - low + mid = low + (difference // 2) + + print(f"low: {low}, mid: {mid}, high: {high}") + # stop iteration when the midpoint is equal to low or high, because we did not find it + # if mid <= low or mid >= high: + if low == mid: + return -1 + +nums = [-1, 0, 3, 5, 9, 12] +target = 9 + +nums = [-1, 0, 3, 5, 9, 12] +target = 2 + +nums = [-1, 0, 3, 5, 9, 12] +target = 12 + +nums = [-1, 0, 3, 5, 9, 12] +target = -2 +print(binary_search(nums, target)) + +# def search \ No newline at end of file