Title: Move a number of elements at the beginning of an array to the end of the array, which we call the rotation of the array. Enter a rotation of an incrementing sorted array, outputting the smallest element of the rotated array. For example, enter {1,2,3,4,5} for a rotation of {3,4,5,1,2}, the minimum value of this array is 1.
Algorithm ideas:
1. Rotating an array is characterized by an array of two ordered arrays, where ascending is an example
2. Obtain the start and end of the array, ask mid, and then use Numbers[mid] to compare with Numbers[start],numbers[end] respectively
If Numbers[mid]>=numbers[start]:start=mid, the loop compares the array after mid
If Numbers[mid]<=numbers[end]: end=mid, loop to compare the array before mid
3. Until start and end are adjacent, this time numbers[end] is the smallest number
Note: When Numbers[mid],numbers[start],numbers[end] Three are equal, the minimum value should be found by sequential traversal
#include <iostream>using namespacestd;intShunxu (int* Numbers,intStartintend);intMin (int*numbers,intLengthThrow(Exception) {if(numbers==null| | length<=0) Throwexception"parameter Error! "); intstart=0, end=length-1;//start points to the subscript of the preceding ordered array, and end points to the subscript of the ordered array that follows intMid=start;//initialize mid to start, if the array does not rotate without entering the while loop, return directly to Numbers[0] while(true) { if(start-end==-1)//start vs. end 1 proves that start is the maximum number and end is the smallest number{mid=end; Break; } Mid= (start+end)/2; //if numbers[mid],numbers[start],numbers[end] is equal, sequential traversal is required if(numbers[mid]==numbers[start]&&numbers[mid]==Numbers[end]) { returnShunxu (numbers,start,end); } if(Numbers[mid]>=numbers[start])//This indicates that the minimum number is behind midstart=mid; Else if(Numbers[mid]<=numbers[end])//This indicates that the minimum number is in front of midEnd=mid; } returnNumbers[mid];}//sequential traversal of arrays for minimum valuesintShunxu (int* Numbers,intStartintend) { intmin=Numbers[start]; for(inti=start+1; i<=end;i++) { if(min>numbers[i]) min=Numbers[i]; } returnmin;}intMain () {inta[ -]={1,1,1,0,1}; cout<<min (A,5); return 0;}
Operation Result:
Minimum number of rotated array