mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-02 06:46:18 -04:00
reorganize dir
Signed-off-by: Mia Steinkirch <mia.steinkirch@gmail.com>
This commit is contained in:
parent
1b6f705e7c
commit
a8e71c50db
276 changed files with 23954 additions and 0 deletions
50
ebook_src/real_interview_problems/binary_search.py
Normal file
50
ebook_src/real_interview_problems/binary_search.py
Normal file
|
@ -0,0 +1,50 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
def binary_search(array, value):
|
||||
last, first = len(array), 0
|
||||
|
||||
while first < last:
|
||||
mid = (last - first)//2
|
||||
item = array[mid]
|
||||
|
||||
if item == value:
|
||||
return True
|
||||
|
||||
elif item < value:
|
||||
last = mid
|
||||
|
||||
else:
|
||||
first = mid
|
||||
|
||||
return False
|
||||
|
||||
def binary_search_rec(array, value, first=0, last=None):
|
||||
last = last or len(array)
|
||||
if len(array[first:last]) < 1:
|
||||
return False
|
||||
|
||||
mid = (last - first)//2
|
||||
if array[mid] == value:
|
||||
return True
|
||||
elif array[mid] < value:
|
||||
return binary_search_rec(array, value, first=first, last=mid)
|
||||
else:
|
||||
return binary_search_rec(array, value, first=mid, last=last)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
array = [3, 4, 6, 7, 10, 11, 34, 67, 84]
|
||||
value = 6
|
||||
assert(binary_search(array, value) == True)
|
||||
assert(binary_search_rec(array, value) == True)
|
||||
value = 8
|
||||
assert(binary_search(array, value) == False)
|
||||
assert(binary_search_rec(array, value) == False)
|
||||
array = [8]
|
||||
assert(binary_search(array, value) == True)
|
||||
assert(binary_search_rec(array, value) == True)
|
||||
array = []
|
||||
assert(binary_search(array, value) == False)
|
||||
assert(binary_search_rec(array, value) == False)
|
Loading…
Add table
Add a link
Reference in a new issue