forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary_Search.php
34 lines (24 loc) · 705 Bytes
/
Binary_Search.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
$list = array(3, 4, 25, 45, 78);
$element_to_be_found = 25;
function binary_search($element_to_be_found, $list, $left, $right)
{
if ($left > $right)
return -1;
$mid = ($right + $left) / 2;
if ($list[$mid] == $element_to_be_found)
return $mid + 1;
else if ($list[$mid] > $element_to_be_found)
return binary_search($element_to_be_found,$list,$left,$mid-1);
else
return binary_search($element_to_be_found,$list,$mid+1,$right);
}
$ans = binary_search($element_to_be_found, $list, 0, count($list) - 1);
if($ans == -1)
echo "Element not found";
else
echo "Element found at position $ans";
/*
Output : Element found at position 3
*/
?>