How does "context" and "lessThanFn" work in standard library sort functions?

There are two contexts.

  1. The context passed to the lessThanFn.
    Context is an extra user defined argument passed from sort to the lessThanFn.
    Most of the times Context is not used (set void as type and {} as value).
    It is used in std.mem.sort and in std.mem.sortUnstable.
    Example: Sorting Strings in Zig

  2. The context struct for comparing and swapping:
    Context is a namespace providing two functions:

        pub fn lessThan(ctx: Context, a: usize, b: usize) bool {}
        pub fn swap(ctx: Context, a: usize, b: usize) void {}
    

    This is used with the sortContext functions: std.sort.insertionContext, std.sort.heapContext, std.sort.pdqContext, std.mem.sortContext and std.mem.sortUnstableContext.
    In the lessThan and swap functions, the context argument is the same context type that is used as namespace.


@Mambe welcome to ziggit :slight_smile:

1 Like