From f483906084955040dac3edbe96be009a72e723a4 Mon Sep 17 00:00:00 2001 From: Ali Haider <57058911+alihaider21@users.noreply.github.com> Date: Wed, 19 Oct 2022 22:33:23 +0500 Subject: [PATCH] added binary_search algo --- binary_search.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 binary_search.py diff --git a/binary_search.py b/binary_search.py new file mode 100644 index 0000000..2741ac9 --- /dev/null +++ b/binary_search.py @@ -0,0 +1,34 @@ +# Binary Search in python + + +def binarySearch(array, x, low, high): + + if high >= low: + + mid = low + (high - low)//2 + + # If found at mid, then return it + if array[mid] == x: + return mid + + # Search the left half + elif array[mid] > x: + return binarySearch(array, x, low, mid-1) + + # Search the right half + else: + return binarySearch(array, x, mid + 1, high) + + else: + return -1 + + +array = [3, 4, 5, 6, 7, 8, 9] +x = 4 + +result = binarySearch(array, x, 0, len(array)-1) + +if result != -1: + print("Element is present at index " + str(result)) +else: + print("Not found") \ No newline at end of file