Blogger Information
Blog 7
fans 0
comment 1
visits 5702
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
二分查找(binary_search)
bokewinner
Original
1169 people have browsed it

方法一:函数法

二分查找描述:

  1. 此数组为有序数组

  2. 每次查找都要有中间值($mid = floor($start+$end)/2)

  3. 若要找的值恰好与中间的值相等就返回true,若要找的值比中间的值大,调整$start = $mid + 1($mid+1是因为$mid已经比较过了),若要找的值比中间的值小,调整$end = $mid - 1;

  4. 这函数为递归调用函数(要求大的方面先一层层调用小一级的,相同的方面,直到有已知的数值,再把结果一层层反推到要求的值)

<?php
//用函数法求二分查找
$arr = array(1,2,3,4,5,6,7);
$len = count($arr);
$search = 9;
$start = 0;
$end = $len - 1;
$result = binary_search($arr,$search,$start,$end);
echo "最后结果为:";var_dump($result);
function binary_search($arr,$search,$start,$end)
{
    if($start > $end)
    {
        return false;
    }
    $mid = floor(($start + $end) / 2);
    if($arr[$mid] == $search)
    {
        return true;
    }
    else if($search > $arr[$mid])
    {
        $temp = binary_search($arr,$search,$mid + 1,$end);
        return $temp;
    }else
    {
        $temp = binary_search($arr,$search,$start,$mid - 1);
        return $temp;
    }
}
?>

方法二:直接法

$arr = array(1,2,3,4,5,6,7);
$len = count($arr);
$search = 7;
$start = 0;
$end = $len - 1;
$flag = false;//标志位(来判断是否找到数)
$mid = floor(($start + $end) / 2);
while($start <= $end)//当$start > $end为判断假,退出循环
{
    if($arr[$mid] == $search)
    {
        $flag = true;
        break;
    }else if($arr[$mid] > $search)
    {
        $end = $mid - 1;
        $mid = floor(($start + $end) / 2);
    }else
    {
        $start = $mid + 1;
        $mid = floor(($start + $end) / 2);
    }
}
echo "结果为";var_dump($flag);
?>


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!