From 70f7fcbe13aea402c9b6129dfe39e67800bb3b84 Mon Sep 17 00:00:00 2001 From: abdallah1936 Date: Mon, 15 May 2023 09:55:26 -0700 Subject: [PATCH] DONE --- search.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/search.py b/search.py index 1c03df0..6360506 100644 --- a/search.py +++ b/search.py @@ -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 \ No newline at end of file