3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php echo "Practicing Binary Search <br>"; function printArray($arr){ foreach ($arr as $value) { echo $value.", "; # code... } echo "<br>"; } $list=array(3,6,5,7,13,10,1,8); //--------------------------------------------------------------------- //function echo "Binary Search, recursive method <br>"; function BSearch($num,$list){ sort($list); printArray($list); echo "<br>"; $left=0; $right=count($list)-1; echo "Number to search:".$num."<br>"; $key=floor(recursiveBSearch($num,$list,$left,$right)); echo "The key is ".$key; } function recursiveBSearch($num,$arr,$left,$right){ if($left>$right){ return -1; } $mid=($left+$right)/2; if($arr[$mid]==$num){ return $mid; } else if($arr[$mid]<$num){ return recursiveBSearch($num,$arr,$mid+1,$right); } else if($arr[$mid]>$num){ return recursiveBSearch($num,$arr,$left,$mid-1); } } //----------------------------------------------------------------------------- //calling function BSearch(5,$list); ?>
based on gXgEe
Output for 5.6.0 - 7.3.1
Practicing Binary Search <br>Binary Search, recursive method <br>1, 3, 5, 6, 7, 8, 10, 13, <br><br>Number to search:5<br>The key is 2