Title: The smallest number in a rotated array
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 incrementally sorted 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.
The most intuitive solution to this problem is not difficult, and we can find the smallest element by traversing the array one at a time. The time complexity of this idea is obviously O (n). But this idea does not take advantage of the characteristics of the input rotation array, and certainly does not reach the interviewer's requirements .
We notice that the rotated array can actually be divided into two sorted sub-arrays, and the elements of the preceding sub-arrays are greater than or equal to the elements of the post-face array. We also note that the smallest element is just the dividing line of these two sub-arrays. in the sorted array we can use the binary lookup method to achieve O (LOGN) lookup .
Two-code implementation
#include"stdio.h"#include<iostream>using namespacestd; #include<assert.h>//traverse the sequence to find the minimum valueintNormalfindminval (int*pstart,int*pEnd) {Assert (Pstart! = NULL && PEnd! =NULL); intMin = *pstart++; while(Pend-pstart >=0) { if(Min > *Pstart) {min= *Pstart; } Pstart++; } returnmin;}intSearchmininrotateaarr_1 (int*pstart,int*pEnd) { if(Pstart = = NULL | | pEnd = =NULL) { return-1; } if(Pend-pstart = =1) { return*pEnd; } int*pmid =NULL; PMid= Pstart + (pend-pstart)/2; if(*pmid >= *pstart && *pmid <= *pEnd) { returnNormalfindminval (Pstart, pEnd); } if(*pmid >= *Pstart) {Pstart=PMid; } Else if(*pmid <= *pEnd) {PEnd=PMid; } returnsearchmininrotateaarr_1 (Pstart, pEnd);}//find the smallest number in the rotated arrayintSearchmininrotateaarr (intArr[],intNlen) {Assert (arr! = NULL && nlen >0); int*pstart,*pEnd; Pstart=arr; PEnd= Pstart + Nlen-1; returnsearchmininrotateaarr_1 (Pstart, pEnd);}intA[] = {3,4,5,1,2};intB[] = {1,1,1,0,1,1};intC[] = {1,2,3,4,5};voidMain () {intdata = Searchmininrotateaarr (A,sizeof(a)/sizeof(a[0])); cout<< Data <<Endl; Data= Searchmininrotateaarr (b,sizeof(b)/sizeof(b[0])); cout<< Data <<Endl; Data= Searchmininrotateaarr (c,sizeof(c)/sizeof(c[0])); cout<< Data <<Endl; return;}
Sword refers to offer interview question: 6. Rotate the smallest number in the array