/*
Binary Search
*/
#include<iostream>
using namespace std;
#define size 10
#define start 0
bool BinarySearch(int array[],int num)
{
int p = start,r = size,middle;
while(p<r)
{
middle = (p+r)/2;
if( array[middle] == num )
return true;
else
{
if( array[middle] > num )
{
r = middle-1;
}
else
{
p = middle+1;
}
}
}
return false;
}
int main()
{
int num,array[size];
cout<<"The number list: ";
for(int i=start;i<sizeof(array)/4;i++)
{
array[i] = i;
cout<<array[i]<<" ";
}
cout<<endl<<endl;
cout<<"input number:";
cin>>num;
if( BinarySearch(array,num) == true )
{
cout<<"Find the number in the list: "<<num<<endl;
}
return 0;
}
執行結果:
留言列表