···11-#include "cache.h"
22-#include "mergesort.h"
33-44-/* Combine two sorted lists. Take from `list` on equality. */
55-static void *llist_merge(void *list, void *other,
66- void *(*get_next_fn)(const void *),
77- void (*set_next_fn)(void *, void *),
88- int (*compare_fn)(const void *, const void *))
99-{
1010- void *result = list, *tail;
1111- int prefer_list = compare_fn(list, other) <= 0;
1212-1313- if (!prefer_list) {
1414- result = other;
1515- SWAP(list, other);
1616- }
1717- for (;;) {
1818- do {
1919- tail = list;
2020- list = get_next_fn(list);
2121- if (!list) {
2222- set_next_fn(tail, other);
2323- return result;
2424- }
2525- } while (compare_fn(list, other) < prefer_list);
2626- set_next_fn(tail, other);
2727- prefer_list ^= 1;
2828- SWAP(list, other);
2929- }
3030-}
3131-3232-/*
3333- * Perform an iterative mergesort using an array of sublists.
3434- *
3535- * n is the number of items.
3636- * ranks[i] is undefined if n & 2^i == 0, and assumed empty.
3737- * ranks[i] contains a sublist of length 2^i otherwise.
3838- *
3939- * The number of bits in a void pointer limits the number of objects
4040- * that can be created, and thus the number of array elements necessary
4141- * to be able to sort any valid list.
4242- *
4343- * Adding an item to this array is like incrementing a binary number;
4444- * positional values for set bits correspond to sublist lengths.
4545- */
4646-void *llist_mergesort(void *list,
4747- void *(*get_next_fn)(const void *),
4848- void (*set_next_fn)(void *, void *),
4949- int (*compare_fn)(const void *, const void *))
5050-{
5151- void *ranks[bitsizeof(void *)];
5252- size_t n = 0;
5353-5454- if (!list)
5555- return NULL;
5656-5757- for (;;) {
5858- int i;
5959- size_t m;
6060- void *next = get_next_fn(list);
6161- if (next)
6262- set_next_fn(list, NULL);
6363- for (i = 0, m = n;; i++, m >>= 1) {
6464- if (m & 1)
6565- list = llist_merge(ranks[i], list, get_next_fn,
6666- set_next_fn, compare_fn);
6767- else if (next)
6868- break;
6969- else if (!m)
7070- return list;
7171- }
7272- n++;
7373- ranks[i] = list;
7474- list = next;
7575- }
7676-}
-13
mergesort.h
···11#ifndef MERGESORT_H
22#define MERGESORT_H
3344-/*
55- * Sort linked list in place.
66- * - get_next_fn() returns the next element given an element of a linked list.
77- * - set_next_fn() takes two elements A and B, and makes B the "next" element
88- * of A on the list.
99- * - compare_fn() takes two elements A and B, and returns negative, 0, positive
1010- * as the same sign as "subtracting" B from A.
1111- */
1212-void *llist_mergesort(void *list,
1313- void *(*get_next_fn)(const void *),
1414- void (*set_next_fn)(void *, void *),
1515- int (*compare_fn)(const void *, const void *));
1616-174/* Combine two sorted lists. Take from `list` on equality. */
185#define DEFINE_LIST_MERGE_INTERNAL(name, type) \
196static type *name##__merge(type *list, type *other, \