From 922a9ea9af41774964cb0102941214428f8bd85a Mon Sep 17 00:00:00 2001 From: Kin Learns <109691311+kinlearn@users.noreply.github.com> Date: Fri, 20 Oct 2023 15:17:05 +0530 Subject: [PATCH] Update binary_search.py Made the algorithm order-agnostic --- B/Binary search/binary_search.py | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/B/Binary search/binary_search.py b/B/Binary search/binary_search.py index f0207cd8..b6524995 100644 --- a/B/Binary search/binary_search.py +++ b/B/Binary search/binary_search.py @@ -11,16 +11,25 @@ def binary_search(arr, target): left, right = 0, len(arr) - 1 # Initialize the left and right pointers + ascending = arr[0] <= arr[-1] # Check if the array is in ascending order while left <= right: mid = (left + right) // 2 # Find the middle index if arr[mid] == target: # Check if the middle element is the target return mid - elif arr[mid] < target: # If the target is greater, ignore the left half - left = mid + 1 - else: # If the target is smaller, ignore the right half - right = mid - 1 + if ascending: + if arr[mid] < target: + left = mid + 1 + else: + right = mid - 1 + else: # Handle descending order + if arr[mid] > target: + left = mid + 1 + else: + right = mid - 1 + + return -1 # Return -1 if the target is not found @@ -34,3 +43,13 @@ def binary_search(arr, target): print(f"Element is present at index {result}.") else: print("Element is not present in array.") + +# Example case with descending order +arr_descending = [40, 10, 4, 3, 2] +target = 10 +result = binary_search(arr_descending, target) + +if result != -1: + print(f"Element is present at index {result}.") +else: + print("Element is not present in array.")