输出旋转(例如{3,4,5,1,2}为{1,2,3,4,5}的一个旋转)中最小元素。
代码:
#include <iostream>
#include <exception>
using namespace std;
int minInorder(int *numbers,int index1,int index2){
int result=numbers[index1];
for(int i=index1+1;i<=index2;i++)
{
if(result>numbers[i])
result=numbers[i];
}
return result;
}
int Min(int *numbers,int length)
{
if(numbers==NULL||length<=0)
throw new std::exception("Invalid parameters");
int index=0;
int index2=length-1;
int indexMid=index;
while(numbers[index]>=numbers[index2])
{
if(index2-index==1)
{
//numbers[index2]>numbers[index]?indexMid=index:indexMid=index2;
//不需要这么写的原因是while循环的条件
indexMid=index2;
break;
}
indexMid=(index+index2)/2;
if(numbers[index]==numbers[indexMid]&&numbers[indexMid]==numbers[index2])
return minInorder(numbers,index,index2);
if(numbers[indexMid]>=numbers[index])
index=indexMid;
else if(numbers[indexMid]<=numbers[index2])
index2=indexMid;
}
return numbers[indexMid];
}
void main(){
int a[10];
char flag='y';
while(flag=='y'||flag=='Y')
{
for(int i=0;i<10;i++)
{
cin>>a[i];
}
int temp=Min(a,10);
cout<<temp<<endl;
cout<<"continue?"<<endl;
cin>>flag;
}
}