From 92082e896f620ab3acc8e89589d7841c3f5b5946 Mon Sep 17 00:00:00 2001 From: Urmil Bhavsar Date: Sat, 28 Oct 2023 19:07:41 +0530 Subject: [PATCH] optimize binary search --- Searching/binary_search.py | 37 +++++++++++-------------------------- 1 file changed, 11 insertions(+), 26 deletions(-) diff --git a/Searching/binary_search.py b/Searching/binary_search.py index 696bef6..44ff966 100644 --- a/Searching/binary_search.py +++ b/Searching/binary_search.py @@ -1,38 +1,23 @@ -#Binary_search using python -def binarySearch(arr, l, r, x): +def binary_search(arr, left, right, target): + while left <= right: + mid = (left + right) // 2 - # Check base case - if r >= l: - - mid = l + (r - l) // 2 - - # If element is present at the middle itself - if arr[mid] == x: + if arr[mid] == target: return mid - - # If element is smaller than mid, then it - # can only be present in left subarray - elif arr[mid] > x: - return binarySearch(arr, l, mid - 1, x) - - # Else the element can only be present - # in right subarray + elif arr[mid] < target: + left = mid + 1 else: - return binarySearch(arr, mid + 1, r, x) - - else: - # Element is not present in the array - return -1 + right = mid - 1 + return -1 # Driver Code arr = [2, 3, 4, 10, 40] -x = 10 +target = 10 -# Function call -result = binarySearch(arr, 0, len(arr) - 1, x) +result = binary_search(arr, 0, len(arr) - 1, target) if result != -1: - print("Element is present at index % d" % result) + print(f"Element is present at index {result}") else: print("Element is not present in array")