分类: C/C++
2008-11-01 20:35:08
英文原题:Implement the following function, FindSortedArrayRotation, which takes as its input an array of unique integers that has been sorted in ascending order, then rotated by an unknown amount X where 0 <= X <= (arrayLength - 1). An array rotation by amount X moves every element array[i] to array[(i + X) % arrayLength]. FindSortedArrayRotation discovers and returns X by examining the array. You should be able to do this in less than linear time.
int FindSortedArrayRotation(int *array, int arrayLength)
{
// Insert your implementation here
/*
After rotation the array was divided into 2 parts: array[0…x-1] and array[x…arrayLength-1]. And each part is sorted in ascending order. But array[x-1]>array[x]. This is a turn corner. My idea is use binary_search algorithm to find the turn corner.
Running time is O(log(2)).
*/
int left = 0;
int right = arrayLength – 1;
if(array[left]<= array[right]) return 0;
while(left<=right)
{
int middle = (left+right)/2;
if(array[middle -1] > array[middle]) return middle;
if(array[middle] > array[right]) left = middle + 1;
else right = middle -1;
}
return -1;
}