Sorting - osvaldoandrade/ova-lib GitHub Wiki

Sorting

Read this page when you already have a public list and want in-place list operations such as sorting, reversing, shuffling, binary search, or min/max.

Constructor

The constructor is:

sorter *create_sorter(comparator cmp);

Cleanup is done via the method-table free field: sorter->free(sorter).

Operation Set

Field Meaning
sort(self, lst) sorts the list in place
shuffle(self, lst) shuffles the list in place
reverse(self, lst) reverses the list in place
binary_search(self, lst, item) returns the index of item in a sorted list or -1
swap(self, lst, i, j) swaps two positions
min_max(self, lst, &min, &max) returns both extrema
min(self, lst) returns the minimum element or NULL
max(self, lst) returns the maximum element or NULL
copy(self, src, dest) inserts the source pointers into the destination list

What the Operations Actually Do

sort uses an in-place quicksort over the public list interface.

binary_search assumes the list is already sorted according to the same comparator held by the sorter. If the list is not sorted first, the result has no meaning.

copy copies stored pointers, not payload objects. After the copy, both lists point to the same payloads.

min, max, and min_max return stored pointers, not copies.

Empty-Case Behavior

Sorting an empty list is safe.

min and max return NULL on an empty list.

min_max writes NULL to both outputs on an empty list.

Ownership and Cleanup

The sorter never owns list payloads.

The destination of copy becomes another owner of the list container only, not of the payload objects. If you later free both lists, you still must free shared payloads in the right place in your own program.

Free the sorter with sorter->free(sorter) and free the list containers with their own free method.