Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 32 additions & 21 deletions search.py
Original file line number Diff line number Diff line change
@@ -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