From 42a5430955a22a3e89e380eed14d2694ad3f3ead Mon Sep 17 00:00:00 2001 From: juanedcabrera Date: Mon, 15 May 2023 10:19:37 -0600 Subject: [PATCH] I have something but I want to optimize --- search.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/search.py b/search.py index 1c03df0..d5c1bd2 100644 --- a/search.py +++ b/search.py @@ -19,3 +19,26 @@ Output: 0 Explanation: -1 exists in the list and its index is 0 """ +# setup +def binary_search(array, target): + left = 0 + right = len(array) +# determine the middle + while left < right: +# run through loop to half things + middle = (left + right) // 2 + if array[middle] < target: + left = middle + 1 + else: + right = middle +# check for target + if array[left] == target: + return left + else: + return -1 + + +nums = [-1, 0, 3, 5, 9, 12] +target = -1 +index = binary_search(nums, target) +print(index) \ No newline at end of file