Sort is simple in concept: It sorts a List according to a function that dictates the ordering. The default ordering function is smaller to larger (the function Less).
In[216]:= SeedRandom@345; aList1 = RandomInteger[100, 10]
Out[216]= {84, 52, 80, 41, 53, 24, 22, 0, 47, 42}
In[218]:= {Sort@aList1, Sort[aList1, Less]} // TableForm
We can specify the ordering function that Sort uses.
In[219]:= Sort[aList1, Greater]
Out[219]= {84, 80, 53, 52, 47, 42, 41, 24, 22, 0}
The ordering function always takes two arguments and compares them. Here we Sort by the second element of each sublist.
In[222]:= Sort[{{a, 2, 85}, {c, 1, 0.61}, {d, 3, 5^5}}, #[[2]] < #2[[2]] &]
Out[222]= {{c, 1, 0.61}, {a, 2, 85}, {d, 3, 3125}}
Whatever the algorithmic magic used by Sort to do its job efficiently, note that Slot1 picks out the first element to compare to the second element, which is picked out by Slot2. Here I show a Slot3 as well.
{#1[[2]], #2[[2]], #3[[2]]} & @@ {{a, 2}, {c, 1}, {d, 3}}
{2, 1, 3}
So under the hood Sort must start by doing something like applying the ordering function as a predicate, but then in architecture using the latest, greatest sorting algorithm from the computational complexity literature.
#1[[2]] < #2[[2]] &[{a, 2}, {c, 1}]
False
As holds throughout Mathematica, Sort works on symbolic arguments. If the symbols had been assigned values, of course those values would be used.
In[228]:= Clear[d, b, c, a]; Sort@{d, b, c, a}
Out[228]= {a, b, c, d}
In[229]:= a = 7; b = 2;
Sort@{d, b, c, a}
Out[230]= {2, 7, c, d}
No comments:
Post a Comment