Title Description
Moves the first element of an array to the end of the array, which we call the rotation of the array. Enter a rotation of an incrementally sorted array, outputting the smallest element of a rotated array.
For example: {3,4,5,1,2} is a rotated array of {1,2,3,4,5}, and the smallest element of the array is 1.
Analysis:
Method One:
Because the array's original array is an incrementing array, the array is traversed from the beginning, and the a[i] is less than a[i-1] then the smallest element is found, which is a[i].
1 intFindminnumber (intArr[],intLength) {//arr is an array of rotation, length2 for(intI=1; i<length;i++){3 if(arr[i]<arr[i-1])4 returnArr[i];//found the smallest element5 }6 return-1;//not found, return-17}
Method Two:
With a binary lookup, two pointers point to the first element (P1) and the tail element (P2) of the rotated array, comparing the size of the two pointer intermediate elements (MIDNUM) with the elements at each end.
If P1 is greater than midnum, the element between P1 to Midnum is not moved, the smallest element is in the other half, and P1 points to midnum.
If P1 is less than midnum, the element between P1 to Midnum is changed, the smallest element is in it, and P2 points to midnum.
P2.
Until the last P1 equals P2, the smallest element is found.
1 intFindMinNumber2 (intArr[],intlength) {2 intP1 =0 ;3 intP2 = length-1 ;4 intMid = (P1+P2)/2 ;5 while(p1!=p2) {6 if(arr[p1]>Arr[mid])7 {8P2 =mid;9 }Ten if(arr[p2]<Arr[mid]) { OneP1 =mid; A } - } - returnARR[P1]; the}
The smallest number of offer_11_ rotating arrays