
二分搜索是一种在排序数组中查找元素的更有效的算法。它的工作原理是反复将搜索间隔分成两半。以下是您的二元搜索函数的详细分解:
function binarysearch(array $arr, float|int $x)
{
$low = 0;
$high = count($arr)-1;
// $midindex = (int) ($low + ($high - $low)/2);
$i = 0;
while($low <= $high){
$i++;
$midindex = (int) ($low + (($high - $low)/2)); //the same as intdiv($low + $high, 2);
if($arr[$midindex] == $x){
return "the number {$x} was found in index {$midindex} of the array. the number of iteration was {$i}";
}elseif($x > $arr[$midindex]){
$low = $midindex +1;
echo $low."\n";
}else{
$high = $midindex - 1;
}
}
return "the number {$x} was not found in the array";
}
echo binarysearch([1,2,3,4,5,6,7,8,9,10,44,45,46,47,48,49,50], 45)
函数binarysearch接受两个参数:
线性搜索是用于查找数组中特定元素的最简单的搜索算法之一。让我们分解一下 php 中的 linearsearch 函数。
function linearSearch(array $arr, float|int $x)
{
for($i=0; $i < count($arr); $i++){
if($x === $arr[$i]){
return "The number {$x} was found in index {$i} of the array\n";
}
}
return "The number {$x} was not found in the array\n";
}
echo linearSearch([1,5,6,3,4,11,3,2], 4);
函数 linearsearch 接受两个参数:
以上就是搜索算法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号