From 1e1a716bccd8e1ef64facb254e301170aefaeb38 Mon Sep 17 00:00:00 2001 From: andrew Date: Mon, 15 May 2023 12:07:13 -0400 Subject: [PATCH] Complete deliverable --- search.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/search.py b/search.py index 1c03df0..0bfca7e 100644 --- a/search.py +++ b/search.py @@ -19,3 +19,25 @@ Output: 0 Explanation: -1 exists in the list and its index is 0 """ +import math + +def binary_search(list, target): + window_start = 0 + while True: + if len(list) == 0: + return -1 + midpoint = math.floor(len(list) / 2) + if list[midpoint] == target: + return f"{target} found at list index {midpoint + window_start}" + elif list[midpoint] > target: + list = list[slice(0, midpoint)] + elif list[midpoint] < target: + prev_length = len(list) + list = list[slice(midpoint + 1, len(list))] + window_start = window_start + prev_length - len(list) + +myList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 22, 26, 54, 433, 3422, 5555, 6666, 344444, 5757575757] + +myTarget = 55 + +print(binary_search(myList, myTarget)) \ No newline at end of file