Heim  >  Artikel  >  php教程  >  php顺序查找和二分查找

php顺序查找和二分查找

WBOY
WBOYOriginal
2016-06-13 09:39:551518Durchsuche

<?<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>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:php性能监控扩展xhprofNächster Artikel:PHP学习笔记(1)