Web Toolbar by Wibiya

Pages

Sunday, January 22, 2012

A sorted array is rotated unknown number of times. Find the minimum in the array.

Solution #1: A sorted array rotated unknown number of times will look something like this,

6, 7, 8, 9, 1, 2, 3, 4, 5

We will use modified binary search to find the minimum element in this array. Here is the code,

int findMin(int* arr, int start, int end)
{
    if(start == end)
        return arr[start];

    int mid = (start+end)/2;

    if(arr[mid] < arr[mid-1])
        return arr[mid];
    else if(arr[mid] < arr[end])
        return findMin(arr, start, mid-1);
    else if(arr[mid] > arr[end])
        return findMin(arr, mid+1, end);
}

No comments: