一個數組是由一個遞減數列左移若干位形成的,比如{4,3,2,1,6,5}
是由{6,5,4,3,2,1}左移兩位形成的,在這種數組中
#include<iostream>
#include<cassert>
#include<stack>
using namespace std ;
int FindNumberInLeftShiftSequence(int *A,int nLen,int expectedNum)
{
assert(A!=NULL&&nLen>0);
int start=0;
int end=nLen-1;
while(start<=end)
{
int mid=start+((end-start)>>2);
if(expectedNum==A[mid])
return mid;
if (A[mid]<A[start])
{
if(expectedNum>A[mid])
end=mid-1;
else
start=mid+1;
}
else if(A[mid]>A[start])
{
if(expectedNum<A[mid])
start=mid+1;
else
end=mid-1;
}
else
{
for (int i=start;i<mid;i++)
{
if(A[i]==expectedNum)
return i;
}
start=mid+1;
}
}
return -1;
}
int main()
{
int A[]={6,5,4,3,2,1};
int nLen=sizeof(A)/sizeof(int);
cout<<FindNumberInLeftShiftSequence(A,nLen,0)<<endl;
int B[]={1,1,1,1,0,1};
int nLen2=sizeof(B)/sizeof(int);
cout<<FindNumberInLeftShiftSequence(B,nLen2,0);
return 1;
}
。