簡單描述一下二分查找和順序查找

<?phpphp


class search數組

{this

// 查找的源數組spa

private $array = array(1,2,3,5,7,6,4,8);code

/**it

* 順序查找法io

* @param $val 要查找的值function

*/class

public function query_search($val)foreach

{

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 < $max; $i++)

{

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

if($val == $this->array[$mid])

{

echo '二分查找成功!';

exit(0);

}

else if($val < $this->array[$mid])

{

$max = $mid;

}

else if($val > $this->array[$mid])

{

$min = $mid;

}

}

echo '二分查找失敗!';

}

}

相關文章
相關標籤/搜索