From b4a74c616ba2452bc8a0c30c0c1a797e0a29e987 Mon Sep 17 00:00:00 2001 From: EGORDYU Date: Mon, 15 May 2023 09:49:47 -0600 Subject: [PATCH] deliverable --- search.py | 53 ++++++++++++++++++++++++++++++++--------------------- 1 file changed, 32 insertions(+), 21 deletions(-) diff --git a/search.py b/search.py index 1c03df0..4fcff8d 100644 --- a/search.py +++ b/search.py @@ -1,21 +1,32 @@ -""" -Example 1: -Input: nums = [-1, 0, 3, 5, 9, 12], target = 9 -Output: 4 -Explanation: 9 exists in nums and its index is 4 - -Example 2: -Input: nums = [-1, 0, 3, 5, 9, 12], target = 2 -Output: -1 -Explanation: 2 does not exist in nums so return -1 - -Example 3: -Input: nums = [-1, 0, 3, 5, 9, 12], target = 12 -Output: 5 -Explanation: 12 exists in the list and its index is 5 - -Example 4: -Input: nums = [-1, 0, 3, 5, 9, 12], target = -1 -Output: 0 -Explanation: -1 exists in the list and its index is 0 -""" + +def binary_search(nums, target): + left = 0 + right = len(nums) -1 + + while left <= right: + mid = (left + right) // 2 + + if nums[mid] == target: + return mid + elif nums[mid] < target: + left = mid + 1 + else: + right = mid - 1 + + return -1 + + +nums = [-1, 0, 3, 5, 9, 12] + +target = 9 +print(binary_search(nums, target)) # Output: 4 + +target = 2 +print(binary_search(nums, target)) # Output: -1 + +target = 12 +print(binary_search(nums, target)) # Output: 5 + +target = -1 +print(binary_search(nums, target)) # Output: 0 +