Sunday, May 19, 2013

Given a sorted, shifted array find the minimum element

Given a sorted, shifted array find the minimum element. For example in {3,4,5,1,2} the minimum is 1, in {4,5,1,2,3} the minimum is 1.

Concept of Binary search can be use with little modification.

// finds the smallest number and returns
// it , if not found it returns -1
public static int findSmallest(int a[], int N)
{
if(length==0 || a==NULL)
return -1;

int start=0,end=N-1;

while(start <= end)
{
int mid=(start end)/2;

// this is the standard comparison condition
if(a[mid] > a[mid+1])
return a[mid+1];

// an extra comparison that adds the optimization that
// if the mid element is the smallest one, there will not be
// extra iterations
if(a[mid] < a[mid-1])
return a[mid];

// the left half is in strictly increasing order
// so we search in the second half
if(a[mid] > a[start])
{
start = mid+1;
}
// The array is not rrotated so we simply
// return the first element of the array
else if(a[mid] >= a[start] && a[mid] <= a[end])
return a[0];

// the right half is in strictly increasing order
// and hence we will search in the left half
else
end= mid-1;

}
return -1;
}

No comments: