二分法查找c++实现

时间:2022-10-27 16:36:59
#include <iostream>
using namespace std;

const int array_size = 5;
int binaryMethod(int intArray[],int goal);

int main()
{
	int age[] = {10,20,30,40,50};
	int searchValue = 50;
	int flag = binaryMethod(age,searchValue);
	cout << "flag: " << flag << endl; 
	return 0;
}
int  binaryMethod(int intArray[],int goal)
{
	int low = 0;
	int high = array_size - 1;
	int middle;
	while(low <= high)
	{
		middle = (low + high) / 2;
		if(goal == intArray[middle])
		{
			return intArray[middle];
		}
		if(intArray[middle] > goal)
		{
			high = middle - 1;
		}
		if(intArray[middle] < goal)
		{
			low = middle + 1;
		}
	}
	//如果数组中查找不到所要查找的数字 返回0 
	return 0;
}