Skip to content

Instantly share code, notes, and snippets.

@ackintosh
Created February 12, 2013 10:35
Show Gist options
  • Save ackintosh/4761471 to your computer and use it in GitHub Desktop.
Save ackintosh/4761471 to your computer and use it in GitHub Desktop.
Linear search and Binary search in PHP
<?php
function contains($v, Array $vs)
{
if (count($vs) === 0) return false;
$left = 0;
$right = count($vs) - 1;
while (($left + 1) < $right) {
$mid = $left + ($right - $left) / 2;
if ($v < $vs[$mid]) {
$right = $mid;
} else {
$left = $mid;
}
}
return $vs[$left] === $v;
}
<?php
function contains($v, Array $vs)
{
foreach ($vs as $val) {
if ($v === $val) return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment