carrercup9.3


Given a sorted array of n integers that has been rotated an unknown number of times, give an O(log n) algorithm that finds an element in the array. You may assume that the array was originally sorted in increasing order

给出一个n个整数的已排序的数组,这个数组被旋转(翻转)未知的次数


分析:这个数组被rotated了未知次,那么把这个数组分成两段考虑,前半段这个数组是递增排序的,后半段这个数组也是递增排序的,具体这个分段的地方就依赖于翻转的次数了。这一点比较关键

下面这个算法是solution中给出的,但是有缺陷如果数组中有相同元素的话,这个算法就失效了

#include<iostream>
using namespace std;
//l means lowerbound,u means upperbound

int search(int a[], int l, int u, int x){
	while(l<=u){
		int m=(l+u)/2;
		if(x==a[m])
			return m;
		else if(a[l]<=a[m]){
			if(x>a[m])
				l=m+1;
			else if(x>=a[l])
				u=m-1;
			else
				l=m+1;
		}
		else if(x<a[m])
			u=m-1;
		else if(x<=a[u])
			l=m+1;
		else
			u=m-1;

	}
	return -1;

}
int main(){

	int a[]={15,16,19,20,25,1,3,4,5,7,10,14};
	cout<<search(a,0,11,5);
	system("pause");
	return 0;


}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值