note 106056 added to function.array-search
| From: | stooshie at gmail dot com | Date: | Thu, 06 Oct 2011 09:51:09 +0000 |
| Subject: | note 106056 added to function.array-search | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-183659@lists.php.net to get a copy of this message | ||
Example of a recursive binary search that returns the index rather than boolean.
<?php
// returns the index of needle in haystack
function binSearch($needle, $haystack)
{
// n is only needed if counting depth of search
global $n;
$n++;
// get the length of passed array
$l = count($haystack);
// if length is 0, problem
if($l <= 0)
{
return -1;
}
// get the mid element
$m = (($l+($l%2))/2);
// if mid >= length (e.g. l=1)
if($m >= $l)
{
$m = $m-1;
}
// get the indexed element to compare to the passed element and branch accordingly
$compare = $haystack[$m];
switch(true)
{
case($compare>$needle):
{
// recurse on the lower half
$new_haystack = array_slice($haystack, 0, $m);
$c = count($new_haystack);
$r = binSearch($needle, $new_haystack);
// return current index - (length of lower half - found index in lower half)
return $m - ($c - $r);
break;
}
case($compare<$needle):
{
// recurse on the upper half
$new_haystack = array_slice($haystack, $m, ($l-$m));
$c = count($new_haystack);
$r = binSearch($needle, $new_haystack);
// return current position + found index in upper half
return $m + $r;
break;
}
case($compare==$needle):
{
// found it, so return index
return $m;
break;
}
}
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 134.36.210.168
----
Manual Page -- http://www.php.net/manual/en/function.array-search.php
Edit -- https://master.php.net/note/edit/106056
Del: integrated -- https://master.php.net/note/delete/106056/integrated
Del: useless -- https://master.php.net/note/delete/106056/useless
Del: bad code -- https://master.php.net/note/delete/106056/bad+code
Del: spam -- https://master.php.net/note/delete/106056/spam
Del: non-english -- https://master.php.net/note/delete/106056/non-english
Del: in docs -- https://master.php.net/note/delete/106056/in+docs
Del: other reasons-- https://master.php.net/note/delete/106056
Reject -- https://master.php.net/note/reject/106056
Search -- https://master.php.net/manage/user-notes.php