Update binary_search.py (#129)
This commit is contained in:
parent
71580d2ae9
commit
44a036a925
@ -2,11 +2,10 @@
|
|||||||
|
|
||||||
import random
|
import random
|
||||||
|
|
||||||
rand_num_li = sorted([random.randint(1, 50) for _ in range(10)])
|
|
||||||
target = random.randint(1, 50)
|
|
||||||
|
|
||||||
|
|
||||||
def binary_search(arr, lb, ub, target):
|
def binary_search(arr, lb, ub, target):
|
||||||
|
"""
|
||||||
|
A Binary Search Example which has O(log n) time complexity.
|
||||||
|
"""
|
||||||
if lb <= ub:
|
if lb <= ub:
|
||||||
mid = ub + lb // 2
|
mid = ub + lb // 2
|
||||||
if arr[mid] == target:
|
if arr[mid] == target:
|
||||||
@ -18,7 +17,9 @@ def binary_search(arr, lb, ub, target):
|
|||||||
else:
|
else:
|
||||||
return -1
|
return -1
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
print("List: {}\nTarget: {}\nIndex: {}".format(
|
rand_num_li = sorted([random.randint(1, 50) for _ in range(10)])
|
||||||
rand_num_li, target,
|
target = random.randint(1, 50)
|
||||||
binary_search(rand_num_li, 0, len(rand_num_li) - 1, target)))
|
print("List: {}\nTarget: {}\nIndex: {}".format(
|
||||||
|
rand_num_li, target,
|
||||||
|
binary_search(rand_num_li, 0, len(rand_num_li) - 1, target)))
|
||||||
|
Loading…
Reference in New Issue
Block a user