MathGroup Archive 2005

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Finding Position in an ordered list

"János TÓTH" <janostothmeister at> wrote in message 
news:d868f9$bus$1 at
> Dear All,
> 0. Now I disclose that I am looking for a word in a dictionary.
> 1. Thank for the BinarySearch idea. It is much faster than Position.
> 2. The idea of interpolation in the case of numbers is fantastic.
> 3. However, I tried BinarySearch[{a,b,c},b] without being evaluated.
> Thus, I need further help.
> Thank for all of you.


Apparently the Combinatorica package BinarySearch function only accepts 
numeric keys. We can modify this function to work with any key as follows:

binarysearch[d_, k_, ordf_:Less] :=
Module[{lo = 1, mid, hi = Length[d], c},
   While[lo <= hi,
      If[(c = d[[mid = Quotient[lo + hi, 2]]]) === k, Return[mid]];
      If[ordf[k, c], hi = mid - 1, lo = mid + 1]];
   Return[lo - 1/2]

Then, for your example, we would use the ordering function OrderedQ[{##}]&:

binarysearch[{a, b, c}, b, OrderedQ[{##}] &]

Carl Woll 

  • Prev by Date: Re: goto and label (cont)
  • Next by Date: Re: Output from Export[ ] (suggestion to Wolfram)
  • Previous by thread: Re: Re: Finding Position in an ordered list
  • Next by thread: Re: Finding Position in an ordered list