首頁 >後端開發 >php教程 >php 二分查找

php 二分查找

WBOY
WBOY原創
2016-07-29 09:12:56965瀏覽

二分查找需要數組有序,效率為O(logn)

<code><span><span><?php</span><span>#二分查找</span><span><span>function</span><span>binarySearch</span><span>(Array <span>$arr</span>, <span>$target</span>)</span> {</span><span>$low</span> = <span>0</span>;
        <span>$high</span> = count(<span>$arr</span>) - <span>1</span>;

        <span>while</span>(<span>$low</span> <= <span>$high</span>) {
            <span>$mid</span> = floor((<span>$low</span> + <span>$high</span>) / <span>2</span>);
            <span>#找到元素</span><span>if</span>(<span>$arr</span>[<span>$mid</span>] == <span>$target</span>) <span>return</span><span>$mid</span>;
            <span>#中元素比目标大,查找左部</span><span>if</span>(<span>$arr</span>[<span>$mid</span>] > <span>$target</span>) <span>$high</span> = <span>$mid</span> - <span>1</span>;
            <span>#重元素比目标小,查找右部</span><span>if</span>(<span>$arr</span>[<span>$mid</span>] < <span>$target</span>) <span>$low</span> = <span>$mid</span> + <span>1</span>;
        }

        <span>#查找失败</span><span>return</span><span>false</span>;
    }

    <span>$arr</span> = <span>array</span>(<span>1</span>, <span>3</span>, <span>5</span>, <span>7</span>, <span>9</span>, <span>11</span>);
    <span>$inx</span> = binarySearch(<span>$arr</span>, <span>1</span>);
    var_dump(<span>$inx</span>);
<span>?></span></span></code>
').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

以上就介紹了php 二分查找,包含了面向的內容,希望對PHP教學有興趣的朋友有幫助。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn