>  기사  >  백엔드 개발  >  php顺序查找和二分查找_PHP教程

php顺序查找和二分查找_PHP教程

WBOY
WBOY원래의
2016-07-13 10:34:571025검색

<?<span php
</span><span class</span><span  search
{
</span><span //</span><span  查找的源数组</span>
<span private</span> <span $array</span> = <span array</span>(1,2,3,5,7,6,4,8<span );

</span><span /*</span><span *
* 顺序查找法
* @param $val 要查找的值
</span><span */</span>
<span public</span> <span function</span> query_search(<span $val</span><span )
{
</span><span foreach</span> (<span $this</span>-><span array</span> <span as</span> <span $k</span> => <span $v</span><span )
{
</span><span if</span>(<span $v</span> == <span $val</span><span )
{
</span><span echo</span> '顺序查找成功!'<span ;
</span><span exit</span>(0<span );
}
}

</span><span echo</span> '顺序查找失败!'<span ;
}

</span><span /*</span><span *
* 二分查找法
* @param $val 要查找的值
</span><span */</span>
<span public</span> <span function</span> bin_search(<span $val</span><span )
{
</span><span sort</span>(<span $this</span>-><span array</span><span );

</span><span $min</span> = 0<span ;
</span><span $max</span> = <span count</span>(<span $this</span>-><span array</span><span );

</span><span for</span> (<span $i</span> = <span $min</span>; <span $i</span> < <span $max</span>; <span $i</span>++<span )
{
</span><span $mid</span> = <span ceil</span>((<span $min</span> + <span $max</span>) / 2<span );
</span><span //</span><span  www.jbxue.com</span>
<span if</span>(<span $val</span> == <span $this</span>-><span array</span>[<span $mid</span><span ])
{
</span><span echo</span> '二分查找成功!'<span ;
</span><span exit</span>(0<span );
}
</span><span else</span> <span if</span>(<span $val</span> < <span $this</span>-><span array</span>[<span $mid</span><span ])
{
</span><span $max</span> = <span $mid</span><span ;
}
</span><span else</span> <span if</span>(<span $val</span> > <span $this</span>-><span array</span>[<span $mid</span><span ])
{
</span><span $min</span> = <span $mid</span><span ;
}
}

</span><span echo</span> '二分查找失败!'<span ;
}
}</span>

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/747274.htmlTechArticle? = (1,2,3,5,7,6,4,8 query_search( ( - = ( == '顺序查找成功!' (0 '顺序查找失败!' bin_search( ( - = 0 = ( - ( = ; ; ++ = (( + ) / 2 ( == - [ '二分查找成功!' (0 ( -...
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.