MathGroup Archive 2001

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

Search the Archive

Re: Sorting and Selecting in MultiLevel Lists?


aes wrote:
> 
> Suppose I want to Sort, or Select from, a multilevel list, e.g.
> 
>         myList =  { {x1,y1},  {x2,y2},  {x3,y3}, . . . }
> 
> with a Sort or Select criterion that's some function of the xn and yn values
> 
> For example, I can sort the above list on the value of x^2 + y^2 by using
> 
>     Sort[myList, (Take[#1, 1][[1]]^2 + Take[#1, 2][[1]]^2) <
>                         (Take[#2, 1][[1]]^2 + Take[#2, 2][[1]]^2) &]
> 
> Question:  Is there an easier way to get at the "x" and "y" values associated
> with the #1 and #2 arguments in Sort, or with the # argument in Select, than the
> awkward   Take[#,m][[n]]   notation used here?


If the outer lists in question are large then speed can be an issue. In
that case it is best to use default Sort because comparison evaluations
for the 2-argument form are relatively expensive. To achieve this goal
you can prepend your "sorting value" to each sublist, sort, then remove
it.

sortOnNorm[ll_List] := Map[Rest, Sort[Map[Prepend[#,#.#]&, ll]]]

In[74]:= n = 5;

In[75]:= ll = Table[Random[], {10^n}, {2}];

In[76]:= Timing[sortedll = sortOnNorm[ll];]
Out[76]= {0.88 Second, Null}

For comparison:

In[78]:= sortOnNorm2[ll_List] := Sort[ll, #1.#1 < #2.#2 &]

In[79]:= Timing[sortedll2 = sortOnNorm2[ll];]
Out[79]= {32.46 Second, Null}

In[80]:= sortedll2 === sortedll 
Out[80]= True


Daniel Lichtblau
Wolfram Research


  • Prev by Date: Re: MultiProcessor Kernel.
  • Next by Date: Carriage Return oddity in Mathematica
  • Previous by thread: Sorting and Selecting in MultiLevel Lists?
  • Next by thread: Re: Sorting and Selecting in MultiLevel Lists?