#include "stdio.h"
#include<iostream>//蓝多多算法实验七
#define MAX 100
using namespace std;
int Binary_Search(const int *array, int n, int key)
{
int low = 1;
int high = n;
int mid;
while(low <= high)
{
if (array[0] < array[1])
{
mid = (low + high) / 2;
if (key < array[mid])
high = mid - 1;
else if (key > array[mid])
low = mid + 1;
else
return mid;
}
if (array[0] > array[1])
{
mid = (low + high) / 2;
if (key> array[mid])
high = mid - 1;
else if (key< array[mid])
low = mid + 1;
else
return mid;
}
}
return 0;
}
int main()
{
int MAXSIZE;
int key;
cout<<"please input the size of the array: ";
cin>>MAXSIZE;
int num [MAX];
cout<<"please input a sorted sequence:本程序仅可实现有序序列的查找(即递增或递减)";
for(int i = 0;i < MAXSIZE;i++)
{
cin>>num [i];
}
cout<<'\n'<<"please input the key = ";
cin>>key;
cout<<endl;
int key_find = Binary_Search(num ,MAXSIZE,key);
if(key_find == 0)
cout<<"NOT FOUND!";
else
cout<<"The "<<key<<" is in the "<< key_find + 1 <<" of the sequence!";
system("pause");
return 0;
}
运行结果:略