commit 6746f4e40a7b07dab80766155058d381e435e767
parent cf90c882f738016cc306799617c367e064883c0b
Author: Louis Burda <quent.burda@gmail.com>
Date: Thu, 8 Jun 2023 02:37:38 +0200
Fix bubble sort ordering
Diffstat:
3 files changed, 8 insertions(+), 7 deletions(-)
diff --git a/include/dvec.h b/include/dvec.h
@@ -39,7 +39,7 @@ struct dvec {
const struct allocator *allocator;
};
-typedef bool (*dvec_sort_order_fn)(const void *p1, const void *p2);
+typedef bool (*dvec_sort_order_fn)(const void *p1, const void *p2, void *u);
typedef int (*dvec_search_cmp_fn)(const void *cur, void *user);
int dvec_init(struct dvec *dvec, size_t dsize, size_t cap,
@@ -67,7 +67,7 @@ void *dvec_iter_fwd(const struct dvec *dvec, const void *p);
void *dvec_iter_bwd(const struct dvec *dvec, const void *p);
int dvec_bubble_sort(struct dvec *dvec,
- bool reverse, dvec_sort_order_fn in_order);
+ bool reverse, dvec_sort_order_fn in_order, void *user);
ssize_t dvec_binary_search(struct dvec *dvec, dvec_search_cmp_fn search_cmp,
void *user, ssize_t *lower, ssize_t *higher);
diff --git a/src/dvec.c b/src/dvec.c
@@ -264,7 +264,8 @@ dvec_iter_bwd(const struct dvec *dvec, const void *p)
}
int
-dvec_bubble_sort(struct dvec *dvec, bool reverse, dvec_sort_order_fn in_order)
+dvec_bubble_sort(struct dvec *dvec, bool reverse,
+ dvec_sort_order_fn in_order, void *user)
{
void *cur, *next, *tmp;
size_t i, k;
@@ -279,7 +280,7 @@ dvec_bubble_sort(struct dvec *dvec, bool reverse, dvec_sort_order_fn in_order)
cur = dvec->data;
for (k = 0; k < dvec->len - i; k++) {
next = cur + dvec->dsize;
- if (in_order(cur, next) == !reverse) {
+ if (in_order(cur, next, user) == reverse) {
memcpy(tmp, cur, dvec->dsize);
memcpy(cur, next, dvec->dsize);
memcpy(next, tmp, dvec->dsize);
diff --git a/src/test.c b/src/test.c
@@ -15,12 +15,12 @@ static const char *dvec_err[] = {
};
bool
-str_sort_order(const void *p1, const void *p2)
+str_sort_order(const void *p1, const void *p2, void *user)
{
const char *s1 = *(const char **)p1;
const char *s2 = *(const char **)p2;
- return strcmp(s1, s2) >= 0;
+ return strcmp(s1, s2) <= 0;
}
int
@@ -49,7 +49,7 @@ main(int argc, const char **argv)
*val = argv[i];
}
- rc = dvec_bubble_sort(&dvec, false, str_sort_order);
+ rc = dvec_bubble_sort(&dvec, false, str_sort_order, NULL);
if (rc) LIBDVEC_ERR(rc);
on = dvec_binary_search(&dvec, str_search, "abc", &below, &above);