aboutsummaryrefslogtreecommitdiff
path: root/puzzles.h
diff options
context:
space:
mode:
authorSimon Tatham <anakin@pobox.com>2019-04-05 19:23:21 +0100
committerSimon Tatham <anakin@pobox.com>2019-04-05 19:23:21 +0100
commit5c4d6b8f35e749b269907fd2cdaacc117198807b (patch)
tree906d0d18799b4720150c40852a03c263fd1a3441 /puzzles.h
parentb0c73d5c58bdd4fedd6da94cfb04e2012f47379f (diff)
downloadpuzzles-5c4d6b8f35e749b269907fd2cdaacc117198807b.zip
puzzles-5c4d6b8f35e749b269907fd2cdaacc117198807b.tar.gz
puzzles-5c4d6b8f35e749b269907fd2cdaacc117198807b.tar.bz2
puzzles-5c4d6b8f35e749b269907fd2cdaacc117198807b.tar.xz
New utility routine: sort with a context parameter.
I'm about to have a need to sort an array based on auxiliary data held in a variable that's not globally accessible, so I need a sort routine that accepts an extra parameter and passes it through to the compare function. Sorting algorithm is heapsort, because it's the N log N algorithm I can implement most reliably.
Diffstat (limited to 'puzzles.h')
-rw-r--r--puzzles.h14
1 files changed, 14 insertions, 0 deletions
diff --git a/puzzles.h b/puzzles.h
index 2e6218e..2895fd4 100644
--- a/puzzles.h
+++ b/puzzles.h
@@ -591,6 +591,20 @@ bool findloop_run(struct findloopstate *state, int nvertices,
bool findloop_is_loop_edge(struct findloopstate *state, int u, int v);
/*
+ * Helper function to sort an array. Differs from standard qsort in
+ * that it takes a context parameter that is passed to the compare
+ * function.
+ *
+ * I wrap it in a macro so that you only need to give the element
+ * count of the array. The element size is determined by sizeof.
+ */
+typedef int (*arraysort_cmpfn_t)(const void *av, const void *bv, void *ctx);
+void arraysort_fn(void *array, size_t nmemb, size_t size,
+ arraysort_cmpfn_t cmp, void *ctx);
+#define arraysort(array, nmemb, cmp, ctx) \
+ arraysort_fn(array, nmemb, sizeof(*(array)), cmp, ctx)
+
+/*
* Data structure containing the function calls and data specific
* to a particular game. This is enclosed in a data structure so
* that a particular platform can choose, if it wishes, to compile