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

二分查找示例

PHP中文网
PHP中文网Original
2016-05-23 17:09:531344browse


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;
}

                   

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