Skip to content

Commit 5190660

Browse files
committed
Binary Search Code added
1 parent 624038e commit 5190660

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@
2222

2323

2424
- [Searching](./Searching/)
25-
- Linear Search
26-
- Binary Search
25+
- [Linear Search](./Searching/Linear%20Search)
26+
- [Binary Search](./Searching/Binary%20Search)
2727
- Ternary Search
2828

2929

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
/* Binary Search implementation in PHP */
3+
function binarySearch(Array $arr, $item) {
4+
$low = 0;
5+
$high = count($arr) - 1;
6+
$found = false;
7+
8+
while ($low <= $high) {
9+
$mid = $low + ($high - $low) / 2; //Midpoint of the Search Space
10+
11+
if ($arr[$mid] === $item) { //Found the element
12+
$found = true;
13+
break;
14+
} else {
15+
if ($item < $arr[$mid]) { //Need to search in the left half of the search space
16+
$high = $mid - 1;
17+
} else { //Need to search in the right half of the search space
18+
$low = $mid + 1;
19+
}
20+
}
21+
}
22+
23+
return $found;
24+
}
25+
26+
27+
/************ Testing Binary Search Implementation ***************/
28+
29+
// This list must be sorted. If it is not given as sorted, sort it first, then call the binarySearch method
30+
$testList = array(0, 1, 2, 8, 13, 17, 19, 32, 42);
31+
echo binarySearch($testList, 3) ? 'True' : 'False';
32+
echo PHP_EOL;
33+
echo binarySearch($testList, 13) ? 'True' : 'False';
34+
35+
?>

0 commit comments

Comments
 (0)