二分查找算法1

#include <iostream> //二分查找法一

using namespace std;

int Binary_search(int b[],int value,int n=9)

{

int hight=9,low=0,mid;

while (hight>=low) //注意两者相等的情况

{

mid=(hight+low)/2;

if (value==b[mid])

{

cout << "查找成功!";

return mid;

}else if(value>b[mid]){

low=mid+1;

}else if(value<b[mid]){

hight=mid-1;

}else{}

}

cout << "查找失败!";

return -1;

}

int main()

{

int value;

int a[100]={1,2,3,4,5,6,7,8,9,10};

while (cin >> value) //为什么我一输入小数就跳出循环并且错误!

{

int t;

t=Binary_search(a,value);

for (int i=0;i<10;i++)

{

cout << a[i] << " " ;

}

if (t==-1)

{

}else{

cout<< "下标为:"<<t << endl;

}

}

return 0;

}

你可能感兴趣的:(二分查找)