note 93704 added to function.array-search

From: Date: Wed, 23 Sep 2009 17:21:09 +0000
Subject: note 93704 added to function.array-search
Groups: php.notes 
Request: Send a blank email to php-notes+get-160987@lists.php.net to get a copy of this message
@temporal There's a slight error in your otherwise excellent binary search: you need to correct the probe whenever it ends on a lesser value, not just when it ends on the last element. Here's my version and tests: <?php function array_bisearch($needle, $haystack, $comparator, &$probe) { $high = count($haystack) - 1; $low = 0; while ($high >= $low) { $probe = floor(($high + $low) / 2); $comparison = $comparator($haystack[$probe], $needle); if ($comparison < 0) { $low = $probe + 1; } elseif ($comparison > 0) { $high = $probe -1; } else { return true; } } //The loop ended without a match //Compensate for needle greater than highest haystack element if ($comparator($haystack[$probe], $needle) < 0) { $probe++; } return false; } $needles = array('ab', 'b', 'd'); foreach (array(array('a', 'ab', 'b ', 'ba', 'bb'), array('a', 'ab', 'ca', 'cb')) as $haystack) { sort($haystack); echo 'Haystack:'; var_dump($haystack); foreach ($needles as $needle) { echo 'Needle: '; var_dump($needle); array_bisearch($needle, $haystack, 'strcmp', $probe); if (isset($haystack[$probe])) { var_dump($haystack[$probe]); } else { echo "FAIL\n"; } } } ?> ---- Server IP: 64.71.164.2 Probable Submitter: 173.14.226.131 ---- Manual Page -- http://www.php.net/manual/en/function.array-search.php Edit -- https://master.php.net/note/edit/93704 Del: integrated -- https://master.php.net/note/delete/93704/integrated Del: useless -- https://master.php.net/note/delete/93704/useless Del: bad code -- https://master.php.net/note/delete/93704/bad+code Del: spam -- https://master.php.net/note/delete/93704/spam Del: non-english -- https://master.php.net/note/delete/93704/non-english Del: in docs -- https://master.php.net/note/delete/93704/in+docs Del: other reasons-- https://master.php.net/note/delete/93704 Reject -- https://master.php.net/note/reject/93704 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#160987) next »