Created
February 12, 2013 10:35
-
-
Save ackintosh/4761471 to your computer and use it in GitHub Desktop.
Linear search and Binary search in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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