From 3578d1289291c300af8bfd41903e57f8bb4e3136 Mon Sep 17 00:00:00 2001 From: brogers-97 Date: Mon, 15 May 2023 09:58:50 -0700 Subject: [PATCH] finished deliverable --- search.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/search.py b/search.py index 1c03df0..165aa30 100644 --- a/search.py +++ b/search.py @@ -19,3 +19,36 @@ Output: 0 Explanation: -1 exists in the list and its index is 0 """ + +# distance = high index - low index +# middle = 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, the high index, middle point index. + # continusly iterate until the target is found or we determine the target cannot be found + # check the value at the mid point against the target, stop iterating if target is found. + # if the value at the midpoint is less than the target, slide the window down. + low = 0 + high = len(nums) + mid = high // 2 + + while True: + if nums[mid] == target: + return mid + elif nums[mid] > target: + high = mid + difference = high - low + mid = low + (difference // 2) + else: + low = mid + difference = high - low + mid = low + (difference // 2) + print(f'low:{low}, mid:{mid}, high:{high}') + if mid == low: + return -1 + +print(binary_search([-1, 0, 3, 5, 9, 12], 9 )) +print(binary_search([-1, 0, 3, 5, 9, 12], 2 )) +print(binary_search([-1, 0, 3, 5, 9, 12], 12 )) +print(binary_search([-1, 0, 3, 5, 9, 12], -1 )) \ No newline at end of file