php顺序查找和二分查找示例
代码如下:
<?php class search { // 查找的源数组 private $array = array(1,2,3,5,7,6,4,8); /** * 顺序查找法 * @param $val 要查找的值 */ public function query_search($val) { foreach ($this->array as $k => $v) { if($v == $val) { echo '顺序查找成功!'; exit(0); } } echo '顺序查找失败!'; } /** * 二分查找法 * @param $val 要查找的值 */ public function bin_search($val) { sort($this->array); $min = 0; $max = count($this->array); for ($i = $min; $i < $max; $i++) { $mid = ceil(($min + $max) / 2); if($val == $this->array[$mid]) { echo '二分查找成功!'; exit(0); } else if($val < $this->array[$mid]) { $max = $mid; } else if($val > $this->array[$mid]) { $min = $mid; } } echo '二分查找失败!'; } }
相关推荐
wuxiaosi0 2020-06-28
lickylin 2020-02-29
xhao 2020-06-29
路漫 2020-06-28
tulensa 2020-06-28
natloc 2020-06-27
Jasmineyaoyao 2020-05-11
vivenwan 2020-04-21
Happyunlimited 2020-01-12
范范 2019-12-27
justaipanda 2011-07-21
GhostintheCode 2017-04-14
潇汀 2015-04-03
Eduenth 2009-09-28
数据库成长之路 2019-04-18
whtqsq 2019-02-22
ResysChina 2018-01-15