PHP实现的折半查询算法示例
文章来源:
2020-02-17 16:00
发布者:陈龙
导读很多人在学习C语言时都写了一些有趣的算法,实际上,这些算法也可以用PHP实现,甚至有些算法的代码也比C语言简单,爱站技术频道小编将为您详细介绍PHP实现的折半查询算法示例。?phpheader("Content-type: text/html;
很多人在学习C语言时都写了一些有趣的算法,实际上,这些算法也可以用PHP实现,甚至有些算法的代码也比C语言简单,爱站技术频道小编将为您详细介绍PHP实现的折半查询算法示例。
php;">
$startIndex){
$searchIndex = ceil(($endIndex - $startIndex) / 2);
}else if($endIndex == $startIndex){
$searchIndex = $endIndex;
}else{
$index = -1;
break;
}
$searchIndex += ($startIndex - 1);
echo '检索范围:'.$startIndex.' ~ '.$endIndex.'
检索位置:'.$searchIndex.'检索值为:'.$data[$searchIndex];
echo '
=======================
';
if($data[$searchIndex] == $x){
$index = $searchIndex;
break;
}else if($x > $data[$searchIndex]){
$startIndex = $searchIndex + 1;
}else{
$endIndex = $searchIndex - 1;
}
$number++;
}while($number < count($data));
return $index;
}
function sSort($data, $x, $startIndex, $endIndex){
if($endIndex > $startIndex){
$searchIndex = ceil(($endIndex - $startIndex) / 2);
}else if($endIndex == $startIndex){
$searchIndex = $endIndex;
}else{
return -1;
}
$searchIndex += ($startIndex - 1);
echo '检索范围:'.$startIndex.' ~ '.$endIndex.'
检索位置:'.$searchIndex.'检索值为:'.$data[$searchIndex];
echo '
=======================
';
if($data[$searchIndex] == $x){
return $searchIndex;
}else if($x > $data[$searchIndex]){
$startIndex = $searchIndex + 1;
return sSort($data, $x, $startIndex, $endIndex);
}else{
$endIndex = $searchIndex - 1;
return sSort($data, $x, $startIndex, $endIndex);
}
}
$data = array(1, 3, 4, 6, 9, 11, 12, 13, 15, 20, 21, 25, 33, 34, 35, 39, 41, 44);
$index = qSort($data, 11); // 不用递归的排序方法
$index = sSort($data, 11, 0, count($data) - 1); // 使用递归的排序方法
echo '结果:'.$index;
运行结果:

看完爱站技术频道小编介绍的PHP实现的折半查询算法示例,想必大家都应该心中有数了,总而言之,条条大路通罗马,除了经验,学习也是一条出路。
原文链接:https://js.aizhan.com/develop/php/11588.html
如有疑问请与原作者联系
免责声明:本文章由会员“陈龙”发布如果文章侵权,请联系我们处理,本站仅提供信息存储空间服务如因作品内容、版权和其他问题请于本站联系
上一篇:
PHP简单实现二维数组赋值与遍历功能示例
下一篇:
thinkPHP5分页功能实现方法分析