Services & Resources / Wolfram Forums
MathGroup Archive
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2005

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

Search the Archive

Re: Finding Position in an ordered list

  • To: mathgroup at
  • Subject: [mg57810] Re: Finding Position in an ordered list
  • From: "Carl K. Woll" <carlw at>
  • Date: Thu, 9 Jun 2005 05:17:43 -0400 (EDT)
  • Organization: University of Washington
  • References: <> <> <d868f9$bus$>
  • Sender: owner-wri-mathgroup at

"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