Skip to content

Commit b053c06

Browse files
authored
Added binary search in python (#282)
1 parent 57048da commit b053c06

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

Python/binary_search.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution:
2+
def search(self, nums: List[int], target: int) -> int:
3+
low = 0
4+
high = len(nums) - 1
5+
mid = 0
6+
7+
while low <= high:
8+
9+
mid = (high + low) // 2
10+
11+
# If x is greater, ignore left half
12+
if nums[mid] < target:
13+
low = mid + 1
14+
15+
# If x is smaller, ignore right half
16+
elif nums[mid] > target:
17+
high = mid - 1
18+
19+
# means x is present at mid
20+
else:
21+
return mid
22+
23+
# If we reach here, then the element was not present
24+
return -1
25+

0 commit comments

Comments
 (0)