数据结构之二分查找

从一个数组中查找一个数,并返回这个数的ID:

#include<iostream>
using namespace std;

//从数组{0,1,16,24,35,47,59,62,73,88,99}中查找62,返回下标
int BinarySearch(int *a,int n,int value)
{
	int key=0;
	int lowKey=1;
	int highKey=n;
	while(lowKey<=highKey)
	{
		int midKey=(lowKey+highKey)/2;
		if (a[midKey]>value)
		{
			highKey=midKey-1;
		}
		else if (a[midKey]<value)
		{
			lowKey=midKey+1;
		}
		else
		{
			key=midKey;
			break;
		}
	}
	return key;
}

void main()
{
	int array[]={0,1,16,24,35,47,59,62,73,88,99};
	int n=10;
	int value=62;
	int key = BinarySearch(array,n,value);
	cout<<"The key of Value is: "<<key<<endl;
	system("pause");
}

猜你喜欢

转载自blog.csdn.net/u014571489/article/details/82760142