From 4f11813a892e0a42dbb404486584a348f04e3a0f Mon Sep 17 00:00:00 2001 From: MANSI MISTRY <65220621+MansiLad@users.noreply.github.com> Date: Sat, 24 Oct 2020 00:17:39 +0530 Subject: [PATCH] Update Binary_Search.py used a recursive approach to Binary Search --- Binary_Search/Binary_Search.py | 50 +++++++++++++++++++--------------- 1 file changed, 28 insertions(+), 22 deletions(-) diff --git a/Binary_Search/Binary_Search.py b/Binary_Search/Binary_Search.py index 64e0f67d14..d3ffeb9568 100644 --- a/Binary_Search/Binary_Search.py +++ b/Binary_Search/Binary_Search.py @@ -1,29 +1,35 @@ # Function for Binary Search -def binarySearch(array, desired): - left = 0 - right = len(array) - 1 - - while left <= right: - # Return positon if found - middle = left + int((right - left) / 2) - - if array[middle] == desired: +def BinarySearch(arr, low, high, num): + if(high >= low): + middle = (high + low) // 2 + #if the num is less than the middle number + if(num < arr[middle]): + return BinarySearch(arr, low, middle-1, num) + #if the num is more than the middle number + elif(num > arr[middle]): + return BinarySearch(arr, middle+1, high, num) + else: return middle - elif desired < array[middle]: - right = middle - 1 - elif desired > array[middle]: - left = middle + 1 + else: + return -1 + +arr = [] +n = int(input("Enter number of elements you want in the array: ")) +print("Note: Enter " + str(n) + " numbers in SORTED ORDER") - return -1 +for i in range(n): + element = int(input("Enter element " + str(i+1) + " : ")) + arr.append(element) + +desired = int(input("Enter Element you want to Search: ")) +index = BinarySearch(arr, 0, len(arr)-1, desired) -num = int(input()) -array = [] -for i in range(0, num): - array.append(int(input())) +if(index != -1): + print(" ----Number Found at index: " + str(index+1) + " ----") +else: + print("----Number Not Found! Try again----") -desired = int(input()) -print ("Found") if binarySearch(array, desired) != -1 else ("Not Found") ''' Input: @@ -32,7 +38,7 @@ def binarySearch(array, desired): desired = 4 Output: -Found +----Number Found at index: 4 ---- Input: num = 5 @@ -40,5 +46,5 @@ def binarySearch(array, desired): desired = 2 Output: -Not Found +----Number Not Found! Try again---- '''