简单算法(2)二分查找

#include<iostream>
#include<stdio.h>
using namespace std;

int  search(int low, int high,int a[],int key)
{
	if (low > high)
		return 0;
	else
	{
		int mid = (low + high) / 2;
		if (key == a[mid])
			return mid;
		else if (key < a[mid])
			return search(low, mid-1, a, key);
		else
			return search(mid+1,high, a, key);
	}
}

int main()
{
	int a[] = { 1,2,3,4,5,6,7,8,9,0 };
	int n = sizeof(a) / sizeof(a[0]);
	cout << n << endl;
	cout << "请输入所要查找的值:8" <<  endl;
	cout << "你所查找的值的位置是:"<< search(0, n, a, 4);
	cout << endl;
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41848006/article/details/81609004