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

二分查找示例

PHP中文网
Release: 2016-05-23 17:09:53
Original
1347 people have browsed it


public function binary_search($int, $array) {
    # 将数组排序
    sort($array);

    # 初始化二分查找的范围
    $lower = 0;
    $upper = count($array) - 1;

    # 进入二分查找流程
    while ($lower  $int) {
            $upper = $middle - 1;
        } elseif ($array[$middle] < $int) {
            $lower = $middle + 1;
        } else {
            return true;
        }
    }

    return false;
}
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template