core/sort
skip to the library navigationShared: available on every enabled target.
Allocation-free in-place heapsort and selection sort using ordering evidence, and heapsort by a comparison given a context.
| Call | What it does |
|---|---|
sort.sort | Heapsort by the items' ordered evidence. |
sort.sort_selection | Selection sort by the same evidence. |
sort.sort_by | Heapsort by a comparison you pass, with a context. |
None of the three allocates, and none promises stability.
Items are constrained on the ordered concept of core/cmp, whose table lists the types ordered ships for. Custom ordered evidence must obey a strict weak ordering.
sort_by takes the order as a comparison, less(by, left, right). On every call it passes the comparison the context by that the caller gave, unchanged. Records that refer into shared storage, such as offsets into one pool of names, are therefore ordered by what they refer to. The context may also be a pointer that the comparison counts through. The comparison must be a strict weak ordering while it runs.
Items
Functions 3
Also on this page
public sort: (item: type is cmp.ordered, values: []mut item) -> none
Sort an initialized mutable slice in place using heapsort: worst-case O(n log n) comparisons, constant auxiliary storage, bounded call depth and no allocation. The cmp.ordered evidence must be a strict weak ordering; equal items need not keep their order.
public sort_by: (item: type, context: type, values: []mut item, by: context,
less: (by: context, left: item, right: item) -> (yes: bool))
-> none
Sort an initialized mutable slice in place by a comparison that is given a context: less(by, left, right) says whether left goes before right, and by is passed to every call unchanged, so items that refer into shared storage, such as offsets into one pool of names, are ordered by what they refer to. Heapsort, as sort is: worst-case O(n log n) comparisons, constant auxiliary storage, bounded call depth and no allocation. less must be a strict weak ordering for as long as the sort runs; equal items need not keep their order.
public sort_selection: (item: type is cmp.ordered, values: []mut item) -> none
Sort in place using selection sort: exactly n(n-1)/2 comparisons, at most n-1 swaps, constant storage, bounded call depth and no allocation. Useful for tiny or swap-expensive views; it is not stable.
Example program
This complete program is one of the compiler's runtime tests. View source.
The program, 16 lines
import core/sort exercise: () -> (ok: bool) = ok = false mut values: [3]i32 = [3, 1, 2] sort.sort(values[0..<3]) ok = values[0] == 1 and values[1] == 2 and values[2] == 3 end exercise public main: () -> (code: i32) = code = 1 ok := exercise() if ok then code = 42 end if end main