Skip to content

Update binary_search.py #203

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions B/Binary search/binary_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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.")