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

#include<iostream>
using namespace std;

int search(int arry[],int begin, int end,int target)
{
	

	
		int mid = (begin + end)/2;
		if(arry[mid] == target)
			return mid;
		else if (arry[mid] < target)
			search(arry,mid + 1,end,target);
		else
			search(arry,begin,mid - 1,target);

}

int main()
{
	int arry[] = {2,4,5,6,7};
	cout << search(arry,0,4,2) << search(arry,0,4,4) << search(arry,0,4,5) << search(arry,0,4,6) << search(arry,0,4,7) << endl;
}


int search(int arry[],int length,int target)
{
	int begin = 0;
	int end = length;

	while(begin != end)
	{
		int mid = (begin + end)/2;
		if(arry[mid] == target)
			return mid;
		else if (arry[mid] < target)
			begin = mid + 1;
		else
			end = mid ;
	}

	return -1;
}

int main()
{
	int arry[] = {2,4,5,6,7};
	cout << search(arry,5,2) << search(arry,5,4) << search(arry,5,5) << search(arry,5,6) << search(arry,5,7) << endl;
}


你可能感兴趣的:(二分查找,递归)