Re: Custom sort a list of pairs

• To: mathgroup at smc.vnet.net
• Subject: [mg73654] Re: Custom sort a list of pairs
• From: Paul Abbott <paul at physics.uwa.edu.au>
• Date: Sat, 24 Feb 2007 02:09:03 -0500 (EST)
• Organization: The University of Western Australia
• References: <ermdtt\$i3t\$1@smc.vnet.net>

In article <ermdtt\$i3t\$1 at smc.vnet.net>, planetmarshalluk at hotmail.com
wrote:

> I've searched through existing posts to no avail, what I want to do is
> this:
> Sort a nested list of pairs, so that each pair is sorted by reverse
> canonical order on its first element, and in normal order on its
> second element.
>
> For example, I want some function
>
> sortPairs[items_]
>
> that when given the input
>
> {{ 1,a},{2,a},{3,a},{1,b},{2,b},{1,c}}
>
> produces the output
>
> {{3,a},{2,a},{2,b}{1,a},{1,b},{1,c}}

>From the Sort documentation, the default ordering function is
OrderedQ[{#1, #2}]&. Since you want to sort by reverse canonical order
on the first element, and in normal order on the second element, the
following construct does what you want:

Sort[ {{1,a},{2,a},{3,a},{1,b},{2,b},{1,c}},
OrderedQ[{First[#2],First[#1]}] &&
OrderedQ[{Last[#1],Last[#2]}]& ]

{{3, a}, {2, a}, {2, b}, {1, a}, {1, b}, {1, c}}

Cheers,
Paul

_______________________________________________________________________
Paul Abbott                                      Phone:  61 8 6488 2734
School of Physics, M013                            Fax: +61 8 6488 1014
The University of Western Australia         (CRICOS Provider No 00126G)
AUSTRALIA                               http://physics.uwa.edu.au/~paul

• Prev by Date: Re: Custom sort a list of pairs
• Next by Date: Re: Custom sort a list of pairs
• Previous by thread: Re: Custom sort a list of pairs
• Next by thread: Re: Custom sort a list of pairs