From 0bdb8a7884b498e1e7c747947cbbeff15b04b784 Mon Sep 17 00:00:00 2001 From: Aditi Jha <62383312+aditijha1302@users.noreply.github.com> Date: Tue, 5 Oct 2021 11:02:47 +0530 Subject: [PATCH] Find index of element using binary search --- binsearch.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 binsearch.py diff --git a/binsearch.py b/binsearch.py new file mode 100644 index 0000000..0c4a566 --- /dev/null +++ b/binsearch.py @@ -0,0 +1,23 @@ +def binarySearch(a, l, r, s): + + if r >= l: + mid = l + (r - l) // 2 + if a[mid] == s: + return mid + elif a[mid] > s: + return binarySearch(a, l, mid-1, s) + else: + return binarySearch(a, mid + 1, r, s) + else: + return -1 + + +n = int(input("Enter number of elements : ")) +a = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n] +s = int(input("Enter the number to be found : ")) + +result = binarySearch(a, 0, len(a)-1, s) +if result != -1: + print("Element is present at index % d" % result) +else: + print("Element is not present")