Re: Sort List of Lists

• To: mathgroup at smc.vnet.net
• Subject: [mg24817] Re: Sort List of Lists
• From: "Allan Hayes" <hay at haystack.demon.co.uk>
• Date: Sun, 13 Aug 2000 23:49:43 -0400 (EDT)
• References: <8n5ipb\$n0o@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```Here are two ways: the first uses the facility to specify the ordering
function for Sort; the second, and much faster one,  manipulates the list so
that we can use the built in ordering functiion

lst = Table[Random[Integer, {0, 9}], {10}, {2}];

s1 = Sort[lst, OrderedQ[{#2[[2]], #1[[2]]}] &]

{{9, 8}, {0, 7}, {8, 6}, {7, 5}, {8, 4}, {6, 3}, {7, 2}, {7, 1}, {6, 0}, {5,
0}}

s2 = Transpose[
Reverse[Transpose[Reverse[Sort[Transpose[Reverse[Transpose[lst]]]]]]]]

{{9, 8}, {0, 7}, {8, 6}, {7, 5}, {8, 4}, {6, 3}, {7, 2}, {7, 1}, {6, 0}, {5,
0}}

As a check compare the list of last entries from the pairs (the actual lists
will not be the same since the the first method ignores the first entries in
the pairs)

s1[[All, 2]] == s2[[All, 2]]

True

---- TIMINGS ----------------------------

lst = Table[Random[Integer, {0, 9}], {10000}, {2}];

(s1 = Sort[lst, OrderedQ[{#2[[2]], #1[[2]]}] &]); // Timing

{12.58 Second, Null}

(s2 = Transpose[
Reverse[Transpose[
Reverse[Sort[Transpose[Reverse[Transpose[lst]]]]]]]]); //
Timing

{0.22 Second, Null}

s1[[All, 2]] == s2[[All, 2]]

True

--
Allan
---------------------
Allan Hayes
Mathematica Training and Consulting
Leicester UK
www.haystack.demon.co.uk
hay at haystack.demon.co.uk
Voice: +44 (0)116 271 4198
Fax: +44 (0)870 164 0565

"dana2" <dan_news at hotmail.com> wrote in message
news:8n5ipb\$n0o at smc.vnet.net...
> Hello.  Could someone please give me a clue on how to sort a list based on
> the Second Element in a List:
> I think one needs to use a "pure function" but I am too new with
Mathematica (v4)
> (Trying to learn though) :>)
>
> For Example, I would like to sort this list based on the second element in
> each sub-list in "Descending" order:
>
> {{9, 2}, {1, 6}, {2, 4}}
>
> Results would be:
> { {1,6},{2,4},{9,2} }
>
>
> I think I will learn a lot about Lists, Sorting, and Pure Functions all in
> one shot  if I could get a hint on how to do this.
> Thank you  very much.  Dana
>
>
>
>
>

```

• Prev by Date: Re: Limitation of ListCorrelate?
• Next by Date: RE: Sort List of Lists
• Previous by thread: RE: Sort List of Lists
• Next by thread: RE: Sort List of Lists