       Re: Sorting and Selecting in MultiLevel Lists?

• To: mathgroup at smc.vnet.net
• Subject: [mg31198] Re: [mg31163] Sorting and Selecting in MultiLevel Lists?
• From: Daniel Lichtblau <danl at wolfram.com>
• Date: Wed, 17 Oct 2001 05:35:21 -0400 (EDT)
• References: <200110140811.EAA02423@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```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][]^2 + Take[#1, 2][]^2) <
>                         (Take[#2, 1][]^2 + Take[#2, 2][]^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:= n = 5;

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

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

For comparison:

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

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

In:= sortedll2 === sortedll
Out= 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?