IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /docs/manual/basics.md). For the complete Mojo documentation index, see llms.txt.
Skip to main content
Version: Nightly
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 to False, 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 a List or Array, because they implicitly convert to a Span.
  • ​cmp_fn (T): The comparison function. The function receives two elements, a and b, and must return True if a should come before b in the sorted result, otherwise it must return False. It must return False even 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 to Copyable and Comparable.
  • ​origin (MutOrigin): The origin of the span.
  • ​stable (Bool): Whether to preserve the relative order of equal elements (defaults to False, 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 a List or Array, because they implicitly convert to a Span.