Re: Does Union[] reliably sort?
- To: mathgroup at smc.vnet.net
- Subject: [mg123686] Re: Does Union[] reliably sort?
- From: "Nasser M. Abbasi" <nma at 12000.org>
- Date: Thu, 15 Dec 2011 04:56:35 -0500 (EST)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
- References: <jca06e$a35$1@smc.vnet.net>
- Reply-to: nma at 12000.org
On 12/14/2011 5:10 AM, Michael Stern wrote: > I have noticed that if combine two lists of date/data objects using > Union[], the result is sorted by date. > > For example > > In[]:= mins={{{2001, 1, 31}, 0.993268}, {{2002, 3, 31}, 1.01395}, > {{2003, 6, 30}, > 1.08647}, {{2005, 11, 30}, 1.14752}, {{2006, 9, 30}, > 1.18938}, {{2007, 2, 28}, 1.19658}, {{2008, 1, 31}, > 1.20432}, {{2011, 1, 31}, 1.37501}}; > In[]:= maxs={{{2000, 10, 31}, 1.01816}, {{2001, 12, 31}, 1.02714}, > {{2004, 2, 29}, > 1.12702}, {{2005, 3, 31}, 1.16986}, {{2010, 10, 31}, 1.39026}}; > > In[]:= Union[maxs, mins] > > Out[]= {{{2000, 10, 31}, 1.01816}, {{2001, 1, 31}, > 0.993268}, {{2001, 12, 31}, 1.02714}, {{2002, 3, 31}, > 1.01395}, {{2003, 6, 30}, 1.08647}, {{2004, 2, 29}, > 1.12702}, {{2005, 3, 31}, 1.16986}, {{2005, 11, 30}, > 1.14752}, {{2006, 9, 30}, 1.18938}, {{2007, 2, 28}, > 1.19658}, {{2008, 1, 31}, 1.20432}, {{2010, 10, 31}, > 1.39026}, {{2011, 1, 31}, 1.37501}} > > Is this reliable behavior? Is there any case in which Union would /not/ > return results that have been properly sorted by date? > > Thank you, > > -Michael Stern A good question. But the Union is the set of all distinct elements in both sets. The result is a set. And a set has no implied order between its elements. It is not a sequence. Hence any order you get is just as good as any other. So, you can't really ask about 'sorting' when it comes to a 'set', because the question does not even apply. I do not know why M returns the Union set sorted. But because any order would just be as good as the other, may be it is just being nice? But you should not depend on the set returned having any specific order. You could always shuffle the set returned if you do not like it being sorted. Quick look at the help does not show an option to Union to remove this 'sorted' feature, but it is easy to shuffle the set if needed. --Nasser
- Follow-Ups:
- Re: reliably sort?
- From: DrMajorBob <btreat1@austin.rr.com>
- Re: reliably sort?
- From: DrMajorBob <btreat1@austin.rr.com>
- Re: reliably sort?