note 37364 modified in function.array-search by vrana

From: Date: Tue, 17 Aug 2004 14:49:02 +0000
Subject: note 37364 modified in function.array-search by vrana
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-79959@lists.php.net to get a copy of this message
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. :) --was-- 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 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. :) http://php.net/manual/en/function.array-search.php

« previous php.notes (#79959) next »