二分法查找在高级点的开发可能会用到了,当然在大公司找工作时都会有面试题是这种了,下面我们来看一篇关于二分法查找在php中实现方法,具体的细节如下所示。
二分法(dichotomie) 即一分为二的方法. 设[a,b]为R的闭区间. 逐次二分法就是造出如下的区间序列([an,bn]):a0=a,b0=b,且对任一自然数n,[an+1,bn+1]或者等于[an,cn],或者等于[cn,bn],其中cn表示[an,bn]的中点.
例子1
header('Content-Type: text/html; charset=utf-8;');
$arr = array(2,33,22,1,323,321,28,36,90,123);
sort($arr);
//二分法查找
echo $index = binarySearch($arr,321);
function binarySearch($arr,$key){
$len = count($arr);
$mid = -1;
$start = 0;
$end = $len-1;
while($start
$mid = (int)(($start+$end)/2);
echo $mid."\n";
if($arr[$mid] == $key){
return $mid;
}else if($arr[$mid]
$start = $mid+1;
}else if($arr[$mid] > $key){
$end = $mid-1;
}
}
}
例子2
//search函数 其中$array为数组,$k为要找的值,$low为查找范围的最小键值,$high为查找范围的最大键值
function search($array, $k, $low=0, $high=0)
{
if(count($array)!=0 and $high == 0) //判断是否为第一次调用
{
$high = count($array);
}
if($low
{
$mid = intval(($low+$high)/2); //取$low和$high的中间值
if ($array[$mid] == $k) //如果找到则返回
{
return $mid;
}
elseif ($k
{
return search($array, $k, $low, $mid-1);
}
else
{
return search($array, $k, $mid+1, $high);
}
}
return -1;
}
$array = array(4,5,7,8,9,10); //测试search函数
echo search($array, 8); //调用search函数并输出查找结果
?>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
