Bootstrap

《算法导论》4、二分查找实现(C++)

#include <iostream>
using namespace std;
int binarySearch(int a[], int p, int q, int target);
void main()
{
	int a[] = { 1,2,3,4,5,6,7,8,9,10 };
	int index=binarySearch(a, 0, 9, 12); //12在数组中不存在
	if (index != -1)
		cout << a[index] << endl;
	else
		cout << "error" << endl;
	system("pause");
}
int binarySearch(int a[], int p, int q, int target)
{
	if (p < q)
	{
		int temp = (p + q) / 2;
		if (a[temp] < target)
			binarySearch(a, temp+1, q, target);   //注意+1
		else if (a[temp] == target)
			return temp;
		else
			binarySearch(a, p, temp-1, target);   //注意-1
	}
	else
	{
		if (a[p] == target)
			return p;
		else
			return -1;
	}
}

;