Wolfram: Sort, Reverse, Order

By Xah Lee. Date: . Last updated: .

General Sort by a Comparison Function

Sort
  • Sort[list]
  • Sort[list, p]

sort a list or any expression.

p is the ordering function that takes 2 args.

in p[a,b], it must return one of:

  • 1 → args order is correct.
  • 0 → args order is considered same.
  • -1 → args order is reversed.

or

  • True → args order is correct.
  • False → args order is reversed.

Sort

Sort[ {3, 5, 2} ]
(* {2, 3, 5} *)

Sort[ {"cat", "dog", "bird"} ]
(* {bird, cat, dog} *)
(* sort by sum *)
Sort[
 {{9, 3}, {1, 0}, {2, 1}},
 Function[{a,b}, Total[ a ] < Total[ b ] ]
]
(* {{1, 0}, {2, 1}, {9, 3}} *)

Sort by a Order Ranking Function

SortBy
  • SortBy[list, f]
  • SortBy[list, {f1, f2, etc}]
  • SortBy[list, f, p]
  • Sort by applying f to items and compare the result.
  • f takes one arg returns a order ranking index, e.g. an integer.
  • When there is a list of f, each successive one is used to break the tie.
  • Predicate p (the ordering function) can be used to break the tie of f
  • The spec for p is the same used for Sort.

SortBy

(* sort by string length *)
SortBy[ {"bird", "dog", "cat"}, StringLength ]
(* {cat, dog, bird} *)

(* note, it also swapped cat and dog, by apply normal sort behavior to string *)
(* sort sum *)
Sort[
{{9, 9, 2}, {2, 3}, {2, 9}},
Function[{x,y}, Total @ x < Total @ y ]
]
(* {{2, 3}, {2, 9}, {9, 9, 2}} *)

Order Ranking Index

Ordering[list]

return a list of indexes that represent how to make the list into order.

Ordering

Ordering[ {55, 88, 44, 99} ]
(* {3, 1, 2, 4} *)

(* this means,
Index 3 of input has order rank of 1.
Index 1 of input has order rank of 2.
Index 2 of input has order rank of 3.
Index 4 of input has order rank of 4.
*)

(* when the list is ordered, the result is 1, 2, 3, etc. *)
Ordering[ {1, 2, 3} ]
{1, 2, 3}
(* to get each element's corresponding order rank, call Ordering twice. *)
Ordering @ Ordering @ {55, 88, 44, 99}
(* {2, 3, 1, 4} *)

(* this means,
55 has a order rank of 2.
88 has a order rank of 3.
44 has a order rank of 1.
99 has a order rank of 4.
*)

Reverse

Reverse[ list ]

reverse a list.

Reverse

Reverse[ {1,2,3,4} ]
(* {4, 3, 2, 1} *)
Reverse[ list, n ]

reverse first n items.

(* reverse first 3 *)
Reverse[ {1,2,3,4}, 3 ]
(* {1, 2, 3, 4} *)
Reverse[ list, {n} ]

reverse items at Level n.

(* reverse order of specific level *)
Reverse[ {{1, 2, {a, b, c}}, 4, {6, 5}}, {2} ]
(* {{{a, b, c}, 2, 1}, 4, {5, 6}} *)
Reverse[ list, {n1,n2,etc} ]

reverse items at several levels.

(* reverse order of several levels *)
Reverse[ {{1, 2, {a, b, c}}, 4, {6, 5}}, {2, 3} ]
(* {{{c, b, a}, 2, 1}, 4, {5, 6}} *)

Cyclic Shift Left Right

RotateRight

shift all elements to the right, last item is moved to first.

RotateRight

RotateRight[ {1, 2, 3, 4} ]

(* {4, 1, 2, 3} *)
RotateLeft

shift all elements to the left, first item is moved to last.

RotateLeft

WolframLang List Operations

WolframLang, Sort