# Sorting: sort

### 5.40.18 Sorting: sort

The sort command sorts lists and expression in various ways.

- sort takes one mandatory argument and one optional argument:
  - L, a list or expression.
  - Optionally, f, a boolean function of two variables (by default, f if the function (x,y) -> x<=y).
- sort(L,f) (for a list L) returns a copy of L sorted according to the order given by f. By default, this means that it will be sorted in increasing order.
- sort(L,f) (for an expression L) returns a copy of L with the terms in sums and products collected and sorted.

Note that using (x,y)->x>=y for f will to sort the list in decreasing order. This may also be used to sort a list of lists (that sort with one argument does not know how to sort).

#### Examples.

- Input:
  sort([3,4,2])
  Output:

  ⎡ ⎣ | 2,3,4 | ⎤ ⎦

- Input:
  sort(exp(2*ln(x))+x*y-x+y*x+2*x)
  Output:

  2 x y+e2 lnx+x

  Input:
  simplify(exp(2*ln(x))+x*y-x+y*x+2*x)
  Output:

  x2+2 x y+x

- Input:
  sort([3,4,2],(x,y)->x>=y)
  Output:

  ⎡ ⎣ | 4,3,2 | ⎤ ⎦