For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).
sort
def sort[T: Copyable, origin: MutOrigin, //, *, stable: Bool = False](span: Span[T, origin], cmp_fn: T)
Sorts a span in place using a custom comparison function.
The comparison function defines the sort order. It receives two elements,
a and b, and returns True if a should come before b in the sorted
result, otherwise it returns False.
For example, this sorts integers in descending order:
var numbers = [3, 1, 4, 1, 5]
def descending(a: Int, b: Int) -> Bool:
return a > b
sort(numbers, descending)
print(numbers) # [5, 4, 3, 1, 1]
Parameters:
- T (
Copyable): The element type of the span. - origin (
MutOrigin): The origin of the span. - stable (
Bool): Whether to preserve the relative order of equal elements (defaults toFalse, elements that compare as equal can end up in a different relative order than they started in).
Args:
- span (
Span[T, origin]): The span to sort. You can directly pass aListorArray, because they implicitly convert to aSpan. - cmp_fn (
T): The comparison function. The function receives two elements,aandb, and must returnTrueifashould come beforebin the sorted result, otherwise it must returnFalse. It must returnFalseeven when the two elements are equal, so it behaves like a strict "less than" comparison.
def sort[T: Comparable & Copyable, origin: MutOrigin, //, *, stable: Bool = False](span: Span[T, origin])
Sorts a span of comparable elements in place in ascending order.
Elements are ordered using the < operator, so the smallest element ends
up first. For example, integers sort from lowest to highest and strings
sort in lexicographic order. To sort in a different order, use the
overload that takes a comparison function, sort(span, cmp_fn).
For example:
var numbers = [3, 1, 4, 1, 5]
sort(numbers)
print(numbers) # [1, 1, 3, 4, 5]
Parameters:
- T (
Comparable&Copyable): The element type of the span. Must conform toCopyableandComparable. - origin (
MutOrigin): The origin of the span. - stable (
Bool): Whether to preserve the relative order of equal elements (defaults toFalse, elements that compare as equal can end up in a different relative order than they started in).
Args:
- span (
Span[T, origin]): The span to sort. You can directly pass aListorArray, because they implicitly convert to aSpan.