Home > Backend Development > PHP Tutorial > php顺序查找和二分查找示例_PHP

php顺序查找和二分查找示例_PHP

WBOY
Release: 2016-06-01 11:55:02
Original
889 people have browsed it

复制代码 代码如下:

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

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

  echo '顺序查找失败!';
 }

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

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

  for ($i = $min; $i   {
   $mid = ceil(($min + $max) / 2);

   if($val == $this->array[$mid])
   {
    echo '二分查找成功!';
    exit(0);
   }
   else if($val array[$mid])
   {
    $max = $mid;
   }
   else if($val > $this->array[$mid])
   {
    $min = $mid;
   }
  }

  echo '二分查找失败!';
 }
}

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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template