From 00c1ddc5c1b1b368cf38f0ae6cd50f13ac5c6b5c Mon Sep 17 00:00:00 2001 From: rahmat-st Date: Mon, 3 Oct 2022 21:58:11 +0700 Subject: [PATCH] Added binary search in python --- Python/binary_search.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Python/binary_search.py diff --git a/Python/binary_search.py b/Python/binary_search.py new file mode 100644 index 00000000..960123c8 --- /dev/null +++ b/Python/binary_search.py @@ -0,0 +1,25 @@ +class Solution: + def search(self, nums: List[int], target: int) -> int: + low = 0 + high = len(nums) - 1 + mid = 0 + + while low <= high: + + mid = (high + low) // 2 + + # If x is greater, ignore left half + if nums[mid] < target: + low = mid + 1 + + # If x is smaller, ignore right half + elif nums[mid] > target: + high = mid - 1 + + # means x is present at mid + else: + return mid + + # If we reach here, then the element was not present + return -1 + \ No newline at end of file