在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
<?php class BinSch{ /* * 二分查找,针对顺序表才有用 */ public function search($arr,$k,$low,$high){ if($low<=$high){ $mid = floor(($low+$high)/2); } if ($arr[$mid] == $k){ return $mid; } if($arr[$mid]>$k){ return $this->search($arr, $k, $low, $mid-1); } if ($arr[$mid]<$k){ return $this->search($arr, $k, $mid+1, $high); } return false; } } class Client{ public static function main(){ $arr = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16); $obj = new BinSch(); echo $obj->search($arr, 10, 0, 15); } } Client::main(); ?> 下面是非递归的二分查找 <?php function serech($arr,$k){ sort($arr); $low = 0; $high = count($arr)-1; while($low<=$high){ $mid = ($low+$high)/2; if($arr[$mid]<$k){ $low = $mid+1; }elseif ($arr[$mid]>$k){ $high = $mid-1; }else { return $arr[$mid]; } } return -1; } $arr = array(1,2,3,4,6,7,8,9); $a = serech($arr,5); var_dump($a);
|
2022-08-17
2022-07-18
2022-11-06
2022-08-17
2022-07-30
请发表评论