php 二分法查找数组中某数值 案例分析

xiaoxiao2021-02-28  131

<?php // 2.二分法查找     //条件1.数组必须是有序的 ;连续的  索引数组;       //比如查找数组中有没有 $a     //原理:1.先比较 $a 和 数组最中间 那个数的大小 假设数组是升序排列     //若$a 比中罕见的数大 在在后半区域 同理查找     //     //案例 使用二分法 查找 下列数组在 有没有25;               function test($arr,$data,$start,$end){                  if($end<$start){             return false;         }         $middle=floor($start+$end);         if($data==$arr[$middle]){             return  $data ;         }else if($data>$arr[$middle]){             //若 查找数比 中间数大 则 向后查找                 return test($arr,$data,$middle+1,$end);         }else if ($data<$arr[$middle]) {                 //若 查找数比 中间数小 则 向前查找                 return test($arr,$data,$start,$middle-1);         }     } $arr=array(10,30,0,50,40); $arr=sort($arr);     $start=0; $end=count($arr)-1; var_dump(test($arr,10,$start,$end));      ?>
转载请注明原文地址: https://www.6miu.com/read-38860.html

最新回复(0)