二分查找

#include <iostream>
using namespace std;
int Binary_search(int A[],int n,int k){
	int left=0,right=n-1;
	while (left<=right)
	{
		int middle=(left+right)/2;
		if (k==A[middle])
		{
			return middle;
		} 
		else if (k>A[middle])
		{
			left=middle+1;
		} 
		else
		{
			right=middle-1;
		}
	}
	return 0;
}
int main(){
	int A[6]={1,3,4,6,77,45};
	int x=Binary_search(A,6,4);
	cout<<(x+1)<<endl;
	return 0;
}

posted @ 2012-05-07 21:19  应律  阅读(128)  评论(0编辑  收藏  举报