Skip to content

Commit c2e136f

Browse files
Merge pull request wangzheng0822#108 from jerryderry/bsearch-variant-python
Binary search variants in python
2 parents 771fe9c + 58aa8bc commit c2e136f

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

python/16_bsearch/bsearch_variants.py

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
"""
2+
Author: Wenru
3+
"""
4+
5+
from typing import List
6+
7+
def bsearch_left(nums: List[int], target: int) -> int:
8+
"""Binary search of the index of the first element
9+
equal to a given target in the ascending sorted array.
10+
If not found, return -1.
11+
"""
12+
low, high = 0, len(nums) - 1
13+
while low <= high:
14+
mid = low + (high - low) // 2
15+
if nums[mid] < target:
16+
low = mid + 1
17+
else:
18+
high = mid - 1
19+
return low if nums[low] == target else -1
20+
21+
def bsearch_right(nums: List[int], target: int) -> int:
22+
"""Binary search of the index of the last element
23+
equal to a given target in the ascending sorted array.
24+
If not found, return -1.
25+
"""
26+
low, high = 0, len(nums) - 1
27+
while low <= high:
28+
mid = low + (high - low) // 2
29+
if nums[mid] <= target:
30+
low = mid + 1
31+
else:
32+
high = mid - 1
33+
return high if nums[high] == target else -1
34+
35+
36+
def bsearch_left_not_less(nums: List[int], target: int) -> int:
37+
"""Binary search of the index of the first element
38+
not less than a given target in the ascending sorted array.
39+
If not found, return -1.
40+
"""
41+
low, high = 0, len(nums) - 1
42+
while low <= high:
43+
mid = low + (high - low) // 2
44+
if nums[mid] < target:
45+
low = mid + 1
46+
else:
47+
high = mid - 1
48+
return low if low < len(nums) else -1
49+
50+
def bsearch_right_not_greater(nums: List[int], target: int) -> int:
51+
"""Binary search of the index of the last element
52+
not greater than a given target in the ascending sorted array.
53+
If not found, return -1.
54+
"""
55+
low, high = 0, len(nums) - 1
56+
while low <= high:
57+
mid = low + (high - low) // 2
58+
if nums[mid] <= target:
59+
low = mid + 1
60+
else:
61+
high = mid - 1
62+
return high if high > 0 else -1
63+
64+
if __name__ == "__main__":
65+
import bisect
66+
67+
a = [0, 1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 10, 10, 10]
68+
b = [11, 12, 12, 13, 14, 14, 15, 15]
69+
print(bisect.bisect_left(a, 10) == bsearch_left(a, 10))
70+
print(bisect.bisect_right(a, 10))
71+
print(bisect.bisect_right(a, 6)-1 == bsearch_right(a, 6))
72+
print(bisect.bisect_right(b, 14)-1 == bsearch_right(b, 14))
73+
74+
print(bsearch_left_not_less(a, 11))
75+
print(bsearch_right_not_greater(b, 12))
76+
print(bsearch_right_not_greater(b, 10))
77+
print(bsearch_right_not_greater(b, 17))

0 commit comments

Comments
 (0)