C Collections

csort · Section 3

csort_sort

csort_sort - sort any collection with custom getter and comparison

C Collections (libccollections, -lccollections)

#include <ccollections/csort.h>
 
bool sorted = csort_sort(collection, length, elem_size, getter_proc,
                         comparison_proc, mprocs);

csort_sort sorts any collection, an array, a vector or a container of
your own, with an iterative mergesort. You give it a getter function to
reach the elements and a comparison function to order them.

collection      Pointer to the collection to sort
length          Number of elements in the collection
elem_size       Size of each element in bytes
getter_proc     Function of type
                void *(*)(void *collection, size_t index) that gives
                a pointer to the storage of the element at an index.
                The sort reads and writes each element through that
                pointer, so the elements don't have to be contiguous
                and a ring buffer, or any other indexed storage, is
                fine. Each pointer must stay valid for the whole
                sort.
comparison_proc Function of type int (*)(const void *, const void *)
                that compares two elements and gives a value less
                than 0, 0, or more than 0, like for qsort(3).
mprocs          Memory management procedures, or NULL for the default
                ones. An mprocs that is not NULL must hold all four of
                malloc, free, calloc and realloc.

Gives true on success, and also in the trivial cases where there is
nothing to do: A NULL collection, a length of 0 or 1, and an elem_size
of 0.
Gives false when length is more than the maximum element count of the
library, when mprocs is not NULL and does not hold all four of malloc,
free, calloc and realloc, when the temporary merge buffer cannot be
allocated, or when length * elem_size overflows size_t. In each of these
cases the collection stays completely unchanged.

The sort is stable, so equal elements keep their relative order. It
takes O(n log n) time in every case and O(n) space for the temporary
merge buffer, and it is iterative, with no recursion.
 
Neither getter_proc nor comparison_proc may be NULL when collection is
not NULL and length is 2 or more. That holds even when elem_size is 0,
although the macro then calls neither of them; only a NULL collection or
a length of 0 or 1 lets a call pass no real procedures. A call that
breaks this rule asserts and aborts the process instead of giving false.

// Sort a plain array
static void *int_at(void *col, size_t i) { return &((int *)col)[i]; }
 
static int int_cmp(const void *a, const void *b) {
  int x = *(const int *)a, y = *(const int *)b;
  return (x > y) - (x < y);
}
 
int arr[] = {3, 1, 2};
if (!csort_sort(arr, 3, sizeof(arr[0]), int_at, int_cmp, NULL)) {
  /* the sort failed: arr does not change */
}

csort_get_default_comparison_proc(3), cvec_sort(3)