您的位置:首页 > 理论基础 > 数据结构算法

微软等数据结构+算法面试100题(39)-- 左旋数组中查找

2012-11-11 20:41 423 查看
一个数组是由一个递减数列左移若干位形成的,比如{4,3,2,1,6,5}

是由{6,5,4,3,2,1}左移两位形成的,在这种数组中查找某一个数。


//递减数组左旋可以分为俩种情况。|| 表示分界处
/*
第一种:6,5,4,3,2,1,||   9,8,7
第二种:3,2,1,||  9,8,7,6,5,4
数组[low....high]。mid=low+(high-low)/2;
如果是p[mid]<=p[low]。那么就是第一种。[low,mid]是有序的。[mid,high]不是有序的。
如果是p[mid]>p[low]。那么就是第而种。[low,mid]是无序的。[mid,high]是有序的。
每一种情况再分要找的元素n和p[mid]的关系。看n是在前半段还是后半段。这样类似于二分查找的思想。
*/
int RotateLeftFindRecursion(int *p,int low,int high,int n)
{
if(low>high)
return -1;
if(low==high)
return p[low]==n?low:-1;

int mid=low+(high-low)/2;
if(p[mid]<=p[low])
{
if(n>=p[mid]&&n<=p[low])
return RotateLeftFindRecursion(p, low,mid,n);
else
return RotateLeftFindRecursion(p, mid+1,high,n);
}
else
{
if(n<=p[mid]&&n>=p[high])
return RotateLeftFindRecursion(p, mid,high,n);
else
return RotateLeftFindRecursion(p, low,mid-1,n);
}
}

void RotateLeftFindTest()
{
int p[]={4,3,2,1,10,9,8,7,6,5};
int len=sizeof(p)/sizeof(int);
cout<<"array : ";
ShowArray(p,len);
int n=0;
while(1)
{
cout<<"n : ";
cin>>n;
int index=RotateLeftFind(p,0,len-1,n);
int index1=RotateLeftFindRecursion(p,0,len-1,n);
cout<<"index : "<<index<<endl;
cout<<"p[index] : "<<p[index]<<endl;
cout<<"index1 : "<<index1<<endl;
cout<<"p[index1] : "<<p[index1]<<endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐