summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAdam Spragg <adam@spra.gg>2023-01-17 14:47:53 +0000
committerAdam Spragg <adam@spra.gg>2023-01-17 16:31:42 +0000
commitaa2614c322cda0be1ff26644d7dead45100ea358 (patch)
tree8afbaaaab9645df4b30c46b0cd9621d297355e0f
parentc7b96550774bd96b86be562491eafe12bf682f51 (diff)
Puzzle 16: Extract function to reverse a series of elements
-rw-r--r--16.c18
1 files changed, 15 insertions, 3 deletions
diff --git a/16.c b/16.c
index 2954ef9..15e9671 100644
--- a/16.c
+++ b/16.c
@@ -26,11 +26,24 @@ qswap(void * base, size_t size, int i, int j)
}
+void
+qreverse(void * base, size_t nmemb, size_t size)
+{
+ size_t i, j;
+
+ if (nmemb < 2)
+ return;
+
+ for (i = 0, j = nmemb - 1; i < j; ++i, --j)
+ qswap(base, size, i, j);
+}
+
+
int
qpermute(void * base, size_t nmemb, size_t size,
int(*compar)(const void *, const void *))
{
- size_t pivot, next = 0, i, j;
+ size_t pivot, next = 0, i;
if (nmemb < 2)
// No other permutations!
@@ -64,8 +77,7 @@ qpermute(void * base, size_t nmemb, size_t size,
qswap(base, size, pivot, next);
// Reverse all the elements after the new pivot
- for (i = pivot + 1, j = nmemb - 1; i < j; ++i, --j)
- qswap(base, size, i, j);
+ qreverse(base + (pivot + 1) * size, nmemb - (pivot + 1), size);
return 1;
}