From 44a036a9259b171f2f4578539441a3ba7fc0c705 Mon Sep 17 00:00:00 2001 From: Tanuj Dhiman <56601466+tanujdhiman@users.noreply.github.com> Date: Sun, 27 Jun 2021 23:01:11 +0530 Subject: [PATCH] Update binary_search.py (#129) --- coding/python/binary_search.py | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/coding/python/binary_search.py b/coding/python/binary_search.py index 2fd753c..cb4fefb 100644 --- a/coding/python/binary_search.py +++ b/coding/python/binary_search.py @@ -2,11 +2,10 @@ 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): + """ + A Binary Search Example which has O(log n) time complexity. + """ if lb <= ub: mid = ub + lb // 2 if arr[mid] == target: @@ -18,7 +17,9 @@ def binary_search(arr, lb, ub, target): else: return -1 - -print("List: {}\nTarget: {}\nIndex: {}".format( - rand_num_li, target, - binary_search(rand_num_li, 0, len(rand_num_li) - 1, target))) +if __name__ == '__main__': + rand_num_li = sorted([random.randint(1, 50) for _ in range(10)]) + target = random.randint(1, 50) + print("List: {}\nTarget: {}\nIndex: {}".format( + rand_num_li, target, + binary_search(rand_num_li, 0, len(rand_num_li) - 1, target)))