note 93594 deleted from function.array-search by danbrown

From: Date: Thu, 17 Sep 2009 16:38:58 +0000
Subject: note 93594 deleted from function.array-search by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-160797@lists.php.net to get a copy of this message
Note Submitter: bryan at magidrimix dot com ---- 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; } ?>

« previous php.notes (#160797) next »