Skip to content

Instantly share code, notes, and snippets.

@midorikocak
Created May 15, 2017 17:44
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save midorikocak/646c59e4042877220ee3a98b371d9c2b to your computer and use it in GitHub Desktop.
Save midorikocak/646c59e4042877220ee3a98b371d9c2b to your computer and use it in GitHub Desktop.
Binary Search implementation using PHP
<?php
// This is the text editor interface.
// Anything you type or change here will be seen by the other person in real time.
$array = [5,4,3,2,1];
function binarySearch(int $value, array $array, int $start, int $end){
if($end<$start) return;
$middle = floor(($end + $start)/2);
if($array[$middle]==$value) return true;
elseif ($array[$middle] > $value) return binarySearch($value, $array, $start, $middle-1);
else binarySearch($value, $array, $middle+1, $end);
}
$found = binarySearch(9 ,$array, 0, sizeof($array)-1);
if($found) echo "found";
else echo "not found";
?>
@AlaaHamoudah
Copy link

You are missing 2 things, sorting the array and returning value of the last "else" statement..
Here is updated and working code
`$array = array(5,4,3,2,1);
//$array = array(1,2,3,4,5);
function binarySearch( $value, array $array, $start, $end){
if($end<$start) return;
sort($array);
$middle = floor(($end + $start)/2);
if($array[$middle]==$value) return true;
elseif ($array[$middle] > $value)
return binarySearch($value, $array, $start, $middle-1);
else
return binarySearch($value, $array, $middle+1, $end);
}
$found = binarySearch(4 ,$array, 0, sizeof($array)-1);

if($found) echo "found";
else echo "not found";`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment