Problem Description: Move a number of the first elements of an array to the end of the array, which we call the rotation of the array. Enter a rotation of the ordered array, outputting the smallest element of the rotated array. For example, the array {3, 4, 5, 1, 2} is a rotation of {1, 2, 3, 4, 5}, and the minimum value of the array is 1.
Train of thought: This problem the most intuitive solution is not difficult. By traversing the array once, you can find the smallest element and the time complexity is obviously O (n). But this idea does not take advantage of the attributes of the input array. Since there is a less time complexity algorithm, it is easy to think of binary lookup because of its time complexity of O (Logn). Can you use a binary search for this problem? The answer is yes. Look at the attributes of the array, first increment (called incrementing a), and then suddenly descend to the minimum and then increment (called Increment b). Of course there is a special case, that is, the array is incremented, the middle does not fall, that is, the number of rotating elements is 0.
For the general case, suppose a is an input array, left and right are the coordinates of the a[mid, and the value of the middle position is examined], if the a[mid] <= A[right], indicating that it is in increment B, and that it adjusts the right-hand side of the line = mid; if A[mid] > = A[left], indicating an increment of a, so adjust left = mid. When the left and right edges are adjacent, the smaller one is the minimum value of the array. In fact, for the general situation, the right boundary refers to the element is the smallest value.
For special cases, the number of rotations is 0. According to the above algorithm, the right side will decrease until it is adjacent to the left boundary. At this point the left boundary refers to the smallest element. Here are a few sets of test cases:
{1,2,3,4,5,6,7,8,9,10} 1
//{4,5,6,7,8,9,10,1,2,3} 1
//{1,1,1,1,1,1,1,1,1,1} 1
//{ 1,9,10,1,1,1,1,1,1,1} 1
//{9,9,9,9,9,9,9,10,1,9}
The result of cluster fifth is wrong. In fact, the above algorithm is suitable for strictly increasing the array, for the non strict increment, the binary method can not guarantee the correct solution. Interested readers, you can try, for not strictly increasing the sequence, whether the binary method can get the correct solution.
Reference code:
function function: the smallest element
//function parameter of rotating array: Parray point to array, len array length
//return value: min element
int findmin (int *parray, int len)
{
if (Parray = NULL | | | len <= 0) return
0;
int left = 0, right = len-1, mid;
while (Right-left!= 1)
{
mid = left + ((right-left) >>1);
if (Parray[right] >= Parray[mid]) Right
= mid;
else if (Parray[left] <= Parray[mid]) left
= mid;
}
return parray[right] > Parray[left]? Parray[left]: parray[right];
}