C++二分法検索

538 ワード

#include 
using namespace std;

template
int BinarySearch(Type a[], const Type& x, int n)
{
	int left = 0; int right = n - 1;
	while (left <= right) {
		int middle = (left + right) / 2;
		if (x == a[middle]) return middle;
		if (x > a[middle])left = middle + 1;
		else right = middle - 1;
	}
}
int main()
{
	int a[100];
	for (int i = 0; i < 100; i++)
		a[i] = i;
	cout << BinarySearch(a, 100, 99) << endl;
	system("pause");
	return 0;
}