note 93594 added to function.array-search
| From: | bryan at magidrimix dot com | Date: | Thu, 17 Sep 2009 16:38:02 +0000 |
| Subject: | note 93594 added to function.array-search | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-160796@lists.php.net to get a copy of this message | ||
The code provided by temporal dot pl at gmail dot com is not quite complete. Because the function
uses the floor() estimating function the loop will needlessly iterate an additional time in the
following scenario:
<?php
$needle = 20;
$haystack = array(10, 30);
$probe = -1;
$res = Array_BinarySearch($needle, $haystack, "CompareNumbers", $probe);
echo (int)$res.' '.$probe.'<br />';
//output should be: 0 1
//output actually is: 0 0
?>
An inelegant fix could be adding an additional compensator conditional just before the needle higher
than highest haystack element:
<?php
//compensate for floor() rounding
if($comparator($haystack[$probe], $needle) < 0)
{
++$probe;
}
?>
----
Server IP: 208.69.120.35
Probable Submitter: 24.173.33.58
----
Manual Page -- http://www.php.net/manual/en/function.array-search.php
Edit -- https://master.php.net/note/edit/93594
Del: integrated -- https://master.php.net/note/delete/93594/integrated
Del: useless -- https://master.php.net/note/delete/93594/useless
Del: bad code -- https://master.php.net/note/delete/93594/bad+code
Del: spam -- https://master.php.net/note/delete/93594/spam
Del: non-english -- https://master.php.net/note/delete/93594/non-english
Del: in docs -- https://master.php.net/note/delete/93594/in+docs
Del: other reasons-- https://master.php.net/note/delete/93594
Reject -- https://master.php.net/note/reject/93594
Search -- https://master.php.net/manage/user-notes.php