Skip to content

MemSort

Description

Generic in-place sort over a flat array of fixed-size items. Quicksort with median-of-three pivot, insertion-sort fallback for small partitions, tail-iteration on the larger side to bound stack depth at O(log n). Stable across compilers / platforms because we don’t depend on libc’s qsort.

Parameters

Name Direction Description
base in,out Pointer to the first element of the array.
n_items in Number of items in the array.
item_size in Size of each item in bytes.
cmp in Comparator returning <0, 0, >0 like strcmp.

Success

Returns; the array is sorted in ascending order per cmp.

Failure

No failure mode. If n_items < 2 or cmp is NULL the call is a no-op.

Usage example (Cross-references)

Usage examples (Cross-references)
    }
    
    void MemSort(void *base_, size n_items, size item_size, GenericCompare cmp) {
        if (!base_ || !cmp || item_size == 0 || n_items < 2) {
            return;
            u8  *right   = base + (i + 1) * item_size;
            if (left_n < right_n) {
                MemSort(base, left_n, item_size, cmp);
                base = right;
                n    = right_n;
                n    = right_n;
            } else {
                MemSort(right, right_n, item_size, cmp);
                n = left_n;
            }
        }
    
        MemSort(vec->data, vec->length, item_size, comp);
    }
        }
    
        MemSort(data, item_count, item_size, comp);
    
        node = list->head;
Last updated on