`
阿尔萨斯
  • 浏览: 4149383 次
社区版块
存档分类
最新评论

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

 
阅读更多

采用二分查找

#include <iostream>
using namespace std;

int binarySearch(int *a,int first,int last,int value)
{
	int mid = first + (last-first)/2;
	if(a[mid] == value)
		return mid;
	else if(a[mid]<value)
	{
		return binarySearch(a,0,mid,value);
	}
	else
	{
		return binarySearch(a,mid+1,last,value);
	}
}

int find(int *a,int len ,int value)
{
	int first = 1;
	for(;first<len;first++)
	{
		if(a[first]<a[0])
		{
			if(a[first] == value)
				return first;
			first++;
		}
		else
		{
			break;
		}
	}

	if(value == first)
	{
		return first;
	}
	else if(value >first)
	{
		return binarySearch(a,first+1,len,value);
	}
	else
	{
		return binarySearch(a,0,first,value);
	}
}


int main()
{
	int a[] = {4,3,2,1,6,5};
	cout<<find(a,6,3)<<endl;
	return 0;
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics