mirror of
https://hub.njuu.cf/TheAlgorithms/Python.git
synced 2023-10-11 13:06:12 +08:00
create simple binary search (#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
This commit is contained in:
parent
d477a4ddf2
commit
7b3d385ad6
26
searches/simple-binary-search.py
Normal file
26
searches/simple-binary-search.py
Normal file
@ -0,0 +1,26 @@
|
||||
# A binary search implementation to test if a number is in a list of elements
|
||||
|
||||
|
||||
def binary_search(a_list, item):
|
||||
"""
|
||||
>>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42]
|
||||
>>> print(binary_search(test_list, 3))
|
||||
False
|
||||
>>> print(binary_search(test_list, 13))
|
||||
True
|
||||
"""
|
||||
if len(a_list) == 0:
|
||||
return False
|
||||
midpoint = len(a_list) // 2
|
||||
if a_list[midpoint] == item:
|
||||
return True
|
||||
if item < a_list[midpoint]:
|
||||
return binary_search(a_list[:midpoint], item)
|
||||
else:
|
||||
return binary_search(a_list[midpoint + 1 :], item)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import doctest
|
||||
|
||||
doctest.testmod()
|
Loading…
Reference in New Issue
Block a user