<?php /** * 查找 **/ //顺序查找 function normal_search($arr, $val){ $count = count($arr); if($count == 0){ return -1; } for($i=0; $i<$count; $i++){ if($arr[$i] == $val){ return $i; } } return -1; } //二分查找-非递归 function bin_search($arr, $low, $high, $value){ while($low<=$high){ $mid = floor(($low+$high)/2); if($value == $arr[$mid]){ return $mid; }elseif($value < $arr[$mid]){ $high = $mid-1; }else{ $low = $mid+1; } } return false; } //二分查找-递归 function bin_searchTwo($arr, $low, $high, $value){ if($low>$high){ return false; } $mid = floor(($low+$high)/2); if($value == $arr[$mid]){ return $mid; }elseif($value < $arr[$mid]){ return bin_searchTwo($arr, $low, $mid-1, $value); }else{ return bin_searchTwo($arr, $mid+1, $high, $value); } } ?>
时间: 2024-10-08 17:23:40