You are here: Re: Bracketed Search on PHP Array? « PHP Programming Language « IT news, forums, messages
Re: Bracketed Search on PHP Array?

Posted by ZeldorBlat on 07/03/07 22:37

On Jul 3, 6:27 pm, "David T. Ashley" <d...@e3ft.com> wrote:
> "ZeldorBlat" <zeldorb...@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 (d...@e3ft.com)http://www.e3ft.com (Consulting Home Page)http://www.dtashley.com (Personal Home Page)http://gpl.e3ft.com (GPL Publications and Projects)

You said there were a few hundred elements in your array. In practice
you won't notice any performance difference between either of those
two methods (or any other, for that matter).

Google for "Premature Optimization" and see what you come up with.

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация