|
Posted by David T. Ashley on 07/03/07 22:27
"ZeldorBlat" <zeldorblat@gmail.com> wrote in message
news:1183500186.720943.98580@n2g2000hse.googlegroups.com...
> On Jul 3, 5:25 pm, "David T. Ashley" <d...@e3ft.com> wrote:
>> Given an integer input, I'd like to find the index in the array of the
>> element $array[$i] such that it is equal to or less than the input but
>> $array[$i+1] is larger.
>
> If the array keys are sequential you could use array_reduce like this:
>
> function bracketSearch($arr, $val) {
> return array_reduce($arr, create_function('$v,$w','return $w > ' .
> $val . ' ? $v : ++$v;'), -1);
> }
>
> Alternatively you could just do it the really easy way:
>
> function bracketSearch($arr, $val) {
> foreach($arr as $k => $v)
> if($v <= $val)
> return $k;
> }
I would prefer to avoid both of those methods, because interpreting PHP code
is likely to be MUCH slower than using a built-in function.
For my application, there is another way to do it; but in the general case
seems like PHP needs another search function.
Although ... a standard binary search might not perform badly, even in PHP,
as it should be O(log N).
--
David T. Ashley (dta@e3ft.com)
http://www.e3ft.com (Consulting Home Page)
http://www.dtashley.com (Personal Home Page)
http://gpl.e3ft.com (GPL Publications and Projects)
Navigation:
[Reply to this message]
|