php算法---二分菠菜源码开发

<?php
菠菜源码开发【企 娥:217 1793 408】
//二分法查询
$erfen = function ($list,$item) {
$low = 0;
$high = count($list) - 1;
$i = 1;
do{
$mid = intval(($low + $high)/2);
$guess = $list[$mid];
echo '执行了'.$i.'次<br />';
$i++;
if($guess == $item) {
return $mid.'<br />';
}else if($guess > $item) {
$high = $mid - 1;
}else if($guess < $item){
$low = $mid + 1;
}else{
return 'none';
}
}while($low <= $high);
};
//普通线性查询
$puton = function($list,$item) {
$i = 1;
if(is_array($list)) {
foreach($list as $key => $value) {
echo '执行了'.$i.'次<br />';
$i++;
if($value == $item) {
return $key.'<br />';
}
}
}else{
return 'none';
}
};
//设置一个较大的数组
$my_arr = range(1,100000);
//寻找较大的数字
print_r($erfen($my_arr,'100000')); //第一种若达到亿级的数据还是会非常快
print_r($puton($my_arr,'100000')); //第二种若达到万级的数据会非常慢

猜你喜欢

转载自blog.51cto.com/13943209/2165383