Write a python program to implement binary search for a given list of elements which are sorted in descending order.
Added 2 weeks ago
Active
Viewed 24
Ans

# Function to perform binary search on a descending order sorted list

def binary_search_desc(arr, target):
    left, right = 0, len(arr) - 1

    while left <= right:
        mid = (left + right) // 2

        # Check if target is at mid
        if arr[mid] == target:
            return mid  # Target found at index mid
        
        # If target is greater, discard the right half
        elif arr[mid] < target:
            right = mid - 1
        
        # If target is smaller, discard the left half
        else:
            left = mid + 1

    return -1  # Target not found

# Example usage
arr = [50, 40, 30, 20, 10]
target = 30

# Perform binary search
result = binary_search_desc(arr, target)

if result != -1:
    print(f"Element {target} found at index {result}")
else:
    print(f"Element {target} not found in the list")


Related Questions