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

I’m pretty new to zig, so to learn the language better I’ve recently been implementing a variety of sorting algorithms in zig, and I now want to convert them to a similar style to the standard library sorting algorithms. The only problem is that I’m not really sure how the “context” parameter works in said sorting algorithms.

From reading the standard library code it seems to only really be used when calling @TypeOf(context) (such as in the type for “lessThanFn”), but I’m not sure what the type of it is supposed to be since whenever I’ve seen the sorting functions be called its just been inputted as “{}” . For example

std.mem.sort(u8, &array, {}, comptime std.sort.asc(u8));

In the actual input parameters it’s type seems to just be anytype.

Could someone explain how “context” works, and what it’s purpose is?

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

I think this might have helped. Thanks :slight_smile:

1 Like