c++二分查找

#include "stdafx.h"
#include<iostream>
using namespace std;
#define N 15
//折半查找:适用于事先排好序的数组

int _tmain(int argc, _TCHAR* argv[])
{
	int a[N]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
	int i;
	cout<<"原数组为:"<<endl;
	for(i=0;i<N;i++)
                cout<<a[i]<<"  ";
	cout<<endl;
	int x,left=0,right=N-1,m;
	cout<<"请输入一个数:"<<endl;
	cin>>x;
	while(left<=right)//当最左边的数的下标小于最右边数的下标时,循环进行
	{
		m=(left+right)/2;
		if(x==a[m])  break;//此时在数组中找到了该数
		else if(x>a[m]) left=m+1;
		else right=m-1;

	}
	if(left<=right) cout<<"该数是数组中的第"<<m<<"个元素"<<endl;
	else cout<<"无此数"<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43090158/article/details/86211775