3

The question: A sorted array A[ ] with distinct elements is rotated at some unknown point, the task is to find the minimum element in it.

Expected Time Complexity: O(Log n)
My code:

def binarySearch(arr, n): 
    s = 0
    e = n-1
    while e >= s: 
        mid = (s+e) // 2
        if e==s:
            return arr[e]
        if mid == s and arr[mid] < arr[mid+1]:
            return arr[mid]
        elif mid == e and arr[mid] < arr[mid-1]:
            return arr[mid]
        elif arr[mid] < arr[mid - 1] and arr[mid] < arr[mid+1]:
            return arr[mid]
        elif arr[mid] < arr[e]:
            e = mid - 1
        else:
            e = mid + 1

When I use the Array = [10, 20, 30, 40, 50, 5, 7], I get the answer = 10, whereas, it should be 5.
What could the error be?
EDIT: Following the answer, I also had to add the following line to consider one case that's left

if e==s:
    return arr[e]

1 Answer 1

4

Does this involve just a normal binary search?

def binarySearch(arr, n): 
    s = 0
    e = n-1
    while e >= s: 
        mid = (s+e) // 2
        if e == s:
            return arr[e]
        elif mid == s and arr[mid] < arr[mid+1]:
            return arr[mid]
        elif mid == e and arr[mid] < arr[mid-1]:
            return arr[mid]
        elif arr[mid] < arr[mid - 1] and arr[mid] < arr[mid+1]:
            return arr[mid]
        elif arr[mid] < arr[e]:
            e = mid - 1
        else:
            s = mid + 1

I think your last line should be s = mid + 1 instead of e = mid + 1.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.