Skip to content

Commit 63e5087

Browse files
arturobp3tstreamDOTh
authored andcommitted
Added new Binary Search algorithm in PHP (#426)
1 parent da338f8 commit 63e5087

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
function binarySearch($list, $item){
4+
$leftIndex = 0;
5+
$rightIndex = sizeof($list);
6+
7+
while($leftIndex <= $rightIndex){
8+
$middleIndex = intdiv(($leftIndex + $rightIndex), 2);
9+
10+
if($list[$middleIndex] < $item){
11+
$leftIndex = $middleIndex + 1;
12+
}
13+
else if ($list[$middleIndex] > $item){
14+
$rightIndex = $middleIndex - 1;
15+
}
16+
else{
17+
return $middleIndex;
18+
}
19+
}
20+
return -1;
21+
}
22+
23+
// Simple demonstration of the function
24+
$array = array(1, 2, 4, 5, 6, 8, 9, 10, 14);
25+
echo binarySearch($array, 8);
26+
?>

0 commit comments

Comments
 (0)