天天看点

C++ 二分查找的递归与非递归实现

非常简单的东西,直接看看代码。

/*二分查找的递归与非递归实现*/
#include <iostream>
using namespace std;
//设定为非重复的递增整数列:循环方法
int BinarySearch(int array[],int value,int length)
{
	if(array == NULL || length < 1)
		return -1;
	int lp = 0;
	int rp = length -1;
	while(rp > lp)
	{
		int mid = (lp + rp)/ 2;
		if(array[mid] == value)
			return mid;
		if(array[mid] > value)
			rp = mid -1;
		else
			lp = mid +1;
	}
}
//递归方法
int binarySearch(const int array[],int value,int lp, int rp)
{
	if(array == NULL||lp > rp)
		return -1;
	int mid = (lp + rp)/2;
	if(array[mid] == value)
		return mid;
	else
	{
		if(array[mid] > value)
			binarySearch(array,value,lp,mid-1);
		else
			binarySearch(array,value,mid+1,rp);
	}
}
int main()
{
	const int length = 10;
	int a[length] = {1,2,3,4,5,6,7,8,9,100};
	cout <<"the loop result is: "<<BinarySearch(a,100,length)<<endl;
	cout <<"the recursion result is: "<<binarySearch(a,100,0,length-1)<<endl;
	system("PAUSE");
	return 0;
}
           

继续阅读