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

PHP二分查找实例

PHP中文网
Release: 2016-05-25 17:10:52
Original
1043 people have browsed it


<?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);
?>
Copy after login

                   

Related labels:
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template