
本文操作系统:windows7系统、PHP5.6版本、DELL G3电脑。
1.定义
二分查找也称折半查找(Binary Search),它是一种效率非常高效的查找方法。但是折半查找要求线性表必须采用顺序存储结构,而且表中元素按关键字有序排列。
2. 优缺点
优点是比较次数少,查找速度快,平均性能好;
其缺点是要求待查表为有序表,且插入删除困难。
因此折半查找方法适用于不经常变动而查找频繁的有序列表。
3.实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | #include<stdio.h>
#include<iostream>
using namespace std;
int main(){
int a[100];
int guess;
int flag=0;
int count=0;
int low=0,mid,high=99;
cout<< "1、初始化" <<endl;
for (int i=0;i<100;i++){
a[i]=i+1;
}
cout<< "2、要查找的数字" <<endl;
cout<< "guess:" ;
cin>>guess;
cout<< "3、二分查找" <<endl;
while (low<=high){
count++;
mid=(low+high)/2;
cout<< "第" <<count<< "次查找,其中low=" <<low<< " high=" <<high<< " mid=" <<mid<<endl;
if (guess==a[mid]){
flag=1;
cout<< "success!比较次数:" <<count<< "次" <<endl;
break ;
}
if (guess>a[mid]){
low=mid+1;
}
if (guess<a[mid]){
high=mid-1;
}
}
if (flag==0)
cout<< "fail!" <<endl;
}
|
以上就是php数组中二分查找的基本介绍,相信大家对于这种查找方法,还是有很多使用的需求的。在接下来的学习中,我们会带来更多有关二分查找的内容,大家可以关注一下。更多php学习指路:php数组