数据结构-折半查找-C++

 折半查找非递归算法

#include<iostream>

using namespace std;

int BinSearch(int arr[], int n, int target)
{
	int l = 0, r = n - 1;
	while (l <=r )
	{
		int mid = l + (r - l) / 2;
		if (arr[mid] == target)
			return mid;
		if (arr[mid] < target)
			l = mid + 1;
		else
			r = mid - 1;
	}
	return -1;
}

int main()
{
	int a[10] = { 1,2,3,4,5,6,7,8,9,10 };
	int res = BinSearch(a, 10, 3);
	cout << res << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40088702/article/details/87978495