Sort

Sort[list]

sorts the elements of list into canonical order.

Sort[list,p]

sorts using the ordering function p.

Details

  • Sort by default orders integers, rational, and approximate real numbers by their numerical values.
  • Sort orders complex numbers by their real parts, and in the event of a tie, by the absolute values of their imaginary parts.
  • Sort orders symbols by their names, and in the event of a tie, by their contexts.
  • Sort usually orders expressions by putting shorter ones first, and then comparing parts in a depthfirst manner.
  • Sort treats powers and products specially, ordering them to correspond to terms in a polynomial.
  • Sort orders strings as in a dictionary, with uppercase versions of letters coming after lowercase ones. Sort places ordinary letters first, followed in order by script, Gothic, doublestruck, Greek, and Hebrew. Mathematical operators appear in order of decreasing precedence.
  • Sort[list,p] applies the ordering function p to pairs of elements in list to determine whether they are in order. The default function p is Order.
  • The ordering function p applied to a pair of elements e1, e2 may return either 1, 0, -1 or True, False. The value of p[e1,e2] is interpreted as follows:
  • 1e1 comes before e2
    0e1 and e2 should be treated as identical
    -1e1 comes after e2
    Truee1 and e2 are in order
    Falsee1 and e2 are out of order
  • Sort can be used on expressions with any head, not only List.

Examples

open allclose all

Basic Examples  (5)

Sort a list:

In[1]:=
Click for copyable input
Out[1]=

Sort using Greater as the ordering function:

In[1]:=
Click for copyable input
Out[1]=
In[2]:=
Click for copyable input
Out[2]=

Sort by comparing the second part of each element:

In[1]:=
Click for copyable input
Out[1]=

Sort elements in an Association according to their values:

In[1]:=
Click for copyable input
Out[1]=

Sort Association in reverse order:

In[1]:=
Click for copyable input
Out[1]=

Scope  (3)

Generalizations & Extensions  (1)

Applications  (5)

Properties & Relations  (7)

Possible Issues  (2)

Neat Examples  (1)

See Also

ReverseSort  SortBy  NumericalSort  AlphabeticSort  TakeSmallest  TakeLargest  Ordering  Order  OrderedQ  Orderless  Median  Quantile  Nearest

Tutorials

Introduced in 1988
(1.0)
| Updated in 2017
(11.1)