From f4be48d1dd43d4c73a71b615a088a2ca2b7ab649 Mon Sep 17 00:00:00 2001 From: CuriousCoder321 <66026995+CuriousCoder321@users.noreply.github.com> Date: Thu, 6 Oct 2022 12:08:16 +0530 Subject: [PATCH] Create binary.py The binary search algorithm is a very important one, and requires you to create a list of numbers between 0 and an upper limit, with every succeeding number having a difference of 2 between them. When the user inputs a random number to be searched the program begins its search by dividing the list into two halves. First, the first half is searched for the required number and if found, the other half is rejected and vice versa. The search continues until the number is found or the subarray size becomes zero. Signed-off-by: CuriousCoder321 <66026995+CuriousCoder321@users.noreply.github.com> --- Binary/binary.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Binary/binary.py diff --git a/Binary/binary.py b/Binary/binary.py new file mode 100644 index 0000000..4c6ee7b --- /dev/null +++ b/Binary/binary.py @@ -0,0 +1,43 @@ +# Recursive Binary Search algorithm in Python + +def binarySearch(array, x, low, high): + +if high >= low: + +mid = low + (high - low)//2 + +# If found at mid, return the value + +if array[mid] == x: + +return mid + +# Search the first half + +elif array[mid] > x: + +return binarySearch(array, x, low, mid-1) + +# Search the second half + +else: + +return binarySearch(array, x, mid + 1, high) + +else: + +return -1 + +array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + +x = int(input("Enter a number between 1 and 10:")) + +result = binarySearch(array, x, 0, len(array)-1) + +if result != -1: + +print("Element is present at position" + str(result)) + +else: + +print("Element not found")