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 +