遞歸式 --- 二分查找

#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
	
int Search(vector<int>& v,int left,int right,int key)
{
	int pos = -1;
	if(left <= right)
	{
		int mid = (right - left +1)/2 + left;
		if(key < v[mid])
			pos = Search(v,left,mid-1,key);
		else if(key > v[mid])
		{
			pos = Search(v,mid+1,right,key);
		}
		else
		{
			pos = mid;
		}
	}
	return pos;
}
		
int SearchValue(vector<int> &v,int n,int key)//這個n是長度
{
	if(n<1)
		return -1;
	else
		return Search(v,0,n-1,key);
}
int main()
{
	int n,tmp,value;
	cin>>n;
	vector<int> v;
	for(int i = 0;i<n;i++)
	{
		cin>>tmp;
		v.push_back(tmp);
	}
	cin >> value;
	int index = SearchValue(v,n,value);
	cout<<index;
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章