Create 01_binary_search.php (#13)
This commit is contained in:
committed by
Aditya Bhargava
parent
4631b7a156
commit
7491aa5890
26
01_introduction_to_algorithms/php/01_binary_search.php
Normal file
26
01_introduction_to_algorithms/php/01_binary_search.php
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
function binarySearch($needle, $array) {
|
||||||
|
$low = 0;
|
||||||
|
$high = count($array) - 1;
|
||||||
|
|
||||||
|
while ($low <= $high) {
|
||||||
|
$middle = floor(($low + $high) / 2);
|
||||||
|
|
||||||
|
if ($array[$middle] == $needle) {
|
||||||
|
return $middle;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($array[$middle] > $needle) {
|
||||||
|
$high = $middle - 1;
|
||||||
|
} else {
|
||||||
|
$low = $middle + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$array = [1, 3, 5, 7, 9];
|
||||||
|
echo binarySearch(3, $array) . "\n";
|
||||||
|
echo binarySearch(-1, $array) . "\n";
|
||||||
Reference in New Issue
Block a user