From aa2614c322cda0be1ff26644d7dead45100ea358 Mon Sep 17 00:00:00 2001 From: Adam Spragg Date: Tue, 17 Jan 2023 14:47:53 +0000 Subject: Puzzle 16: Extract function to reverse a series of elements --- 16.c | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) (limited to '16.c') 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; } -- cgit v1.2.1