Sunday 13 January 2013

A sorted array is rotated right by some number. Find the smallest element in O(log n).


/*
print the smallest element in rotated array.
*/

#include<iostream.h>
int main()
{
    int arr[]={6,7,8,9,10,11,12,13,14,1,2,3,4,5};
    int n = sizeof(arr)/sizeof(arr[0]);
    int start =0, end = n-1, mid = (end+start)/2;
    while(start<mid && mid<end)
    {
        if( arr[mid] < arr[mid-1])
        {
            cout<<arr[mid];
            break;
        }
        else if( arr[start] > arr[mid] )
        {
             end = mid;
        }
        else
            start=mid;
        mid = (end+start)/2;
    }
}

No comments:

Post a Comment