二分查找法

#include <iostream>
#include <algorithm>
using namespace std;

// 非递归 
template<typename T>
int binarySearch(T arr[], int n, T target)
{
	int l = 0, r = n - 1;
	while(l <= r)
	{
		int mid = l + (r - l) / 2;
		if(arr[mid] == target)
		{
			return mid + 1;
		}
		else if(arr[mid] < target)
		{
			l = mid + 1;
		}
		else
		{
			r = mid - 1;
		}
	}
	
	return -1;
} 

// 递归 
template<typename T>
int _binarySearch2(T arr[], int l, int r, T target) 
{
	if(l > r)
		return -1;
	
	int mid = l + (r - l) / 2;
	if(arr[mid] == target)
		return mid + 1;
	else if(arr[mid] < target)
		return _binarySearch2(arr, mid + 1, r, target);
	else
		return _binarySearch2(arr, l, mid - 1, target);	
}

template<typename T>
int binarySearch2(T arr[], int n, T target)
{
	return _binarySearch2(arr, 0, n - 1, target);
}

int main()
{
	int arr[] = {1,6,3,9,4};
	sort(arr, arr + 5);	// 对于有序数列才能使用二分查找法 
	int pos;
	pos = binarySearch2(arr, 5, 6);
	cout << pos << endl;
	
	return 0;
}

/*
4
*/

  

posted @ 2019-03-25 16:16  青衫客36  阅读(91)  评论(0编辑  收藏  举报