Home > Backend Development > PHP Tutorial > PHP sequential search and binary search examples_PHP tutorial

PHP sequential search and binary search examples_PHP tutorial

WBOY
Release: 2016-07-13 10:35:00
Original
964 people have browsed it

Copy code The code is as follows:

class search
{
// Search source array
private $array = array(1,2,3,5,7,6,4,8);

/**
* Sequential search method
* @param $val The value to be found
*/
public function query_search($val)
{
foreach ($this->array as $k => $v)
{
if ($v == $val)
{
echo 'Sequential search successful!';
exit(0);
}
}

echo 'Sequential search failed !';
}

/**
* Binary search method
* @param $val The value to be found
*/
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 'Binary search successful!';
exit(0);
}
else if($val < $this->array[$mid])
{
$max = $mid;
}
else if($val > $this->array[$mid])
{
$min = $mid;
}
}

echo 'Binary search failed!';
}
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/746619.htmlTechArticleCopy the code as follows: ?php class search { // Search source array private $array = array(1, 2,3,5,7,6,4,8); /*** Sequential search method * @param $val The value to be found*/ public function...
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