Created
May 15, 2017 17:44
-
-
Save midorikocak/646c59e4042877220ee3a98b371d9c2b to your computer and use it in GitHub Desktop.
Binary Search implementation using PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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"; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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";`