Skip to content

Commit

Permalink
Added new Binary Search algorithm in PHP (Asiatik#426)
Browse files Browse the repository at this point in the history
  • Loading branch information
arturobp3 authored and tstreamDOTh committed Oct 7, 2019
1 parent da338f8 commit 63e5087
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions Searching/Binary Search/PHP/BinarySearch.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

function binarySearch($list, $item){
$leftIndex = 0;
$rightIndex = sizeof($list);

while($leftIndex <= $rightIndex){
$middleIndex = intdiv(($leftIndex + $rightIndex), 2);

if($list[$middleIndex] < $item){
$leftIndex = $middleIndex + 1;
}
else if ($list[$middleIndex] > $item){
$rightIndex = $middleIndex - 1;
}
else{
return $middleIndex;
}
}
return -1;
}

// Simple demonstration of the function
$array = array(1, 2, 4, 5, 6, 8, 9, 10, 14);
echo binarySearch($array, 8);
?>

0 comments on commit 63e5087

Please sign in to comment.