note 37364 deleted from function.array-search by peehaa

From: Date: Fri, 07 Apr 2017 10:34:40 +0000
Subject: note 37364 deleted from function.array-search by peehaa
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-209000@lists.php.net to get a copy of this message
Note Submitter: php at celerondude dot com ---- I think array_search uses serial search because they binary search function i wrote here seems to do a better job for records that are not always at the beginning of the array. Here it is <?php function binarySearch ( $a, $t, $l, $r ) { if($t<$a[$l]||$t>$a[$r])return NULL; while ( $l < $r ) { $m=intval($l+$r)/2; if($a[$m]==$t)return $m; elseif($t<$a[$m])$r=$m-1; elseif($t>$a[$m])$l = $m + 1; } if($t==$a[$r]) return $r; return NULL; } ?> usage: binarySearch ( array, target, left range, right range ); if your array is a multidimensional array, simply change the comparison method. :)

« previous php.notes (#209000) next »