Skip to content

Commit 3da254d

Browse files
praiseartsstokhos
authored andcommitted
create simple binary search (TheAlgorithms#1430)
* create simnple binary search #A binary search implementation to test if a number is in a list of elements * Add .py, format with psf/black, and add doctests
1 parent 418f412 commit 3da254d

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

searches/simple-binary-search.py

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# A binary search implementation to test if a number is in a list of elements
2+
3+
4+
def binary_search(a_list, item):
5+
"""
6+
>>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42]
7+
>>> print(binary_search(test_list, 3))
8+
False
9+
>>> print(binary_search(test_list, 13))
10+
True
11+
"""
12+
if len(a_list) == 0:
13+
return False
14+
midpoint = len(a_list) // 2
15+
if a_list[midpoint] == item:
16+
return True
17+
if item < a_list[midpoint]:
18+
return binary_search(a_list[:midpoint], item)
19+
else:
20+
return binary_search(a_list[midpoint + 1 :], item)
21+
22+
23+
if __name__ == "__main__":
24+
import doctest
25+
26+
doctest.testmod()

0 commit comments

Comments
 (0)