[ Comparing and Sorting | Reference Manual | Alphabetic Index ]
# sort(+Key, +Order, +Random, -Sorted)

Succeeds if Sorted is the sorted list version of Random. The sort is done
according to the Key and Order specifications.
*Key*
- A non-negative integer or a list of positive integers.
*Order*
- One of the atoms <, =<, > or >=.
*Random*
- List.
*Sorted*
- List or variable.

## Description

Sorts the list Random according to the Key and Order specifications, and
unifies Sorted with the result. The sort is stable, i.e. the order of
elements with the same key is preserved.
If Random is not a list of compound terms, use Key = 0.

If Random is a list of compound terms, then the sort will be according
to the Keyth argument of the list elements. If Key = 0, then the sort
is on the entire terms.

In all cases, Order specifies whether the list is sorted into ascending
(<, =<) or descending (>, >=) order and whether duplicates are to be
retained (=<, >=) or eliminated (<, >). The way to remember the Order
argument is that it is the relation which holds between adjacent
elements in the result.

The sort is done according to the standard ordering of terms.
See compare/3 for the definition of this standard ordering.
Note in particular that numbers are first ordered by their type (integer,
float, etc) and only then by their magnitude, i.e. sorting numbers of
different types may not give the expected result.

### Modes and Determinism

### Exceptions

*(5) type error *
- Key is greater than 0, and one of List1 and List2 does not have all elements compound terms.
*(5) type error *
- Key is not an integer or a list of integers.
*(6) out of range *
- One of the compound terms in List1 or List2 has not got as many as Key arguments.

## Examples

Success:
sort(0,<,[3,1,6,7,2],S). (gives S=[1,2,3,6,7]).
sort(0,>,[q,1,3,a,e,N],S).
(gives N=_g78,S=[q,e,a,3,1,_g78]).
sort(0,=<,[1,3,2,3,4,1],S). (gives S=[1,1,2,3,3,4]).
sort(2,<,[f(1,3),h(2,1)],S). (gives S=[h(2,1),f(1,3)]).
sort(1,<,[f(1,3),h(2,1)],S). (gives S=[f(1,3),h(2,1)]).
sort([2,1],=<,[f(3,a(2)),f(1,a(1)),f(0,a(3)),f(1,a(4))],S).
(gives S=[f(1,a(1)),f(3,a(2)),f(0,a(3)),f(1,a(4))]).
Fail:
sort(0,<,[2,1,3,4],[2,1,3,4]).
Error:
sort(1,<,[f(1),f(3),5],S). (Error 5).
sort(1.0,<,[f(1),f(3),f(5)],S). (Error 5).
sort(2,<,[f(1,2),g(3,a),f(5)],S). (Error 6).

## See Also

compare / 3, msort / 2, sort / 2, number_sort / 4