From 93c063bff9479f672d484844495fd82d6d4c4d87 Mon Sep 17 00:00:00 2001 From: Kavin18 <148603725+Kavin56@users.noreply.github.com> Date: Thu, 16 May 2024 17:09:16 +0530 Subject: [PATCH] Create Binary search.py --- Searching algorithms/Binary search.py | 30 +++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Searching algorithms/Binary search.py diff --git a/Searching algorithms/Binary search.py b/Searching algorithms/Binary search.py new file mode 100644 index 0000000..11be022 --- /dev/null +++ b/Searching algorithms/Binary search.py @@ -0,0 +1,30 @@ +def binarySearch(arr, low, high, x): + + if high >= low: + + mid = low + (high - low) // 2 + + if arr[mid] == x: + return mid + + elif arr[mid] > x: + return binarySearch(arr, low, mid-1, x) + + else: + return binarySearch(arr, mid + 1, high, x) + + else: + return -1 + + +if __name__ == '__main__': + arr = list(map(int,input("Enter the array elements: ").split())) + x = int(input("enter the number to search: ")) + + # Function call + result = binarySearch(arr, 0, len(arr)-1, x) + + if result != -1: + print("Element is present at index", result) + else: + print("Element is not present in array")