Home >php教程 >PHP源码 >PHP二分查找实例

PHP二分查找实例

PHP中文网
PHP中文网Original
2016-05-25 17:10:521081browse


<?php
/**二分查找:查找一个值在数组中的位置
* @$arr:操作的数组,前提是按顺序排列
* @$val:查找的值
* @$low:查找的起始位置,默认从数组的第一个数找起
* @hight:查找的结束位置
**/
function binarySearch($arr, $val, $hight, $low=0){
    while($low  $val){
            $hight = $mid -1;
        }else{
            $low = $mid +1;
        }
    }
    return -1;
}
header(&#39;Content-Type:text/html; charset=utf-8&#39;);

//产生一个数组
$arr = range(0,20);
echo &#39;&#39;;
print_r($arr);
echo &#39;&#39;;

$low = 0;
$hight = count($arr) - 1;
$findVal = rand(0, 20);
$index = binarySearch($arr, $findVal, $hight, $low);
printf("查找的值 &#39;%d&#39; 在数组中的下标 &#39;%s&#39;", $findVal, $index);
?>

                   

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn