Home >Backend Development >PHP Tutorial >PHP sequential search and binary search examples_PHP tutorial
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!';
}
}