1. 程式人生 > >c++二分查詢

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;
}