PHP实现的折半查询算法示例
2020-02-17
发布者:陈龙
导读很多人在学习C语言时都写了一些有趣的算法,实际上,这些算法也可以用PHP实现,甚至有些算法的代码也比C语言简单,爱站技术频道小编将为您详细介绍PHP实现的折半查询算法示例。?phpheader("Content-type: text/html;
很多人在学习C语言时都写了一些有趣的算法,实际上,这些算法也可以用PHP实现,甚至有些算法的代码也比C语言简单,爱站技术频道小编将为您详细介绍PHP实现的折半查询算法示例。
php;"> <?php header("Content-type: text/html; charset=utf-8"); function qSort($data = array(), $x = 0){ $startIndex = 0; // 开始索引 $endIndex = count($data) - 1; // 结束索引 $index = 0; $number = 0; // 计数器 do{ if($endIndex > $startIndex){ $searchIndex = ceil(($endIndex - $startIndex) / 2); }else if($endIndex == $startIndex){ $searchIndex = $endIndex; }else{ $index = -1; break; } $searchIndex += ($startIndex - 1); echo '检索范围:'.$startIndex.' ~ '.$endIndex.'<br>检索位置:'.$searchIndex.'检索值为:'.$data[$searchIndex]; echo '<br>=======================<br><br>'; 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.'<br>检索位置:'.$searchIndex.'检索值为:'.$data[$searchIndex]; echo '<br>=======================<br><br>'; 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
如有疑问请与原作者联系
免责声明:本文章由会员“陈龙”发布如果文章侵权,请联系我们处理,本站仅提供信息存储空间服务如因作品内容、版权和其他问题请于本站联系