sort pairs

*To*: mathgroup at yoda.physics.unc.edu*Subject*: sort pairs*From*: nb at eeyore.stanford.edu*Date*: Thu, 11 Nov 93 16:22:45 -0800

> How can I sort pairs of values -- basing the sort on the first value > and then break ties on the second value in the pair. > > Let's say I have n pairs on numbers in the following matrix > > data = { {x1,y1}, .....{xi, yi}, .....{xn,yn} } > > Using the Sort function in Mma, I can easily sort on the xi values, but > how can I do the secondary sort on the yi values?? As you can see from the usage statement, you can specify an ordering function as a second argument to Sort. Sort[list] sorts the elements of list into canonical order. Sort[list, p] sorts using the ordering function p. Below I generate 10 pairs of integers in the range from 1 to 100. In[1]:= data = Table[Random[Integer, {1, 100}], {10}, {2}] Out[1]= {{25, 89}, {75, 81}, {31, 78}, {80, 58}, {65, 87}, {23, 12}, {19, 65}, {92, 97}, {54, 10}, {55, 61}} Using a pure function, I specify an ordering function that compares the second element in two pairs. In[2]:= Sort[data, #2[[2]] > #1[[2]]&] Out[2]= {{54, 10}, {23, 12}, {80, 58}, {55, 61}, {19, 65}, {31, 78}, {75, 81}, {65, 87}, {25, 89}, {92, 97}} The pairs are now sorted according to the value of the second element in each pair. Nancy Blachman