From ab4685070515230c9aa64f9e69eec7fc061ee8d7 Mon Sep 17 00:00:00 2001 From: "Rafael G. Martins" Date: Fri, 26 Apr 2019 19:18:11 +0200 Subject: common: added bc_slist_sort --- src/common/sort.c | 44 ++++++++++++++++++++++++++++++++++++++++++++ src/common/sort.h | 18 ++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 src/common/sort.c create mode 100644 src/common/sort.h (limited to 'src') diff --git a/src/common/sort.c b/src/common/sort.c new file mode 100644 index 0000000..3e24706 --- /dev/null +++ b/src/common/sort.c @@ -0,0 +1,44 @@ +/* + * blogc: A blog compiler. + * Copyright (C) 2014-2019 Rafael G. Martins + * + * This program can be distributed under the terms of the BSD License. + * See the file LICENSE. + */ + +#include +#include "utils.h" +#include "sort.h" + + +bc_slist_t* +bc_slist_sort(bc_slist_t *l, bc_sort_func_t cmp) +{ + if (l == NULL) { + return NULL; + } + + bool swapped = false; + bc_slist_t *lptr = NULL; + bc_slist_t *rptr = NULL; + + do { + swapped = false; + lptr = l; + + while (lptr->next != rptr) { + if (0 < cmp(lptr->data, lptr->next->data)) { + void *tmp = lptr->data; + lptr->data = lptr->next->data; + lptr->next->data = tmp; + swapped = true; + } + + lptr = lptr->next; + } + + rptr = lptr; + } while(swapped); + + return l; +} diff --git a/src/common/sort.h b/src/common/sort.h new file mode 100644 index 0000000..9f4dda2 --- /dev/null +++ b/src/common/sort.h @@ -0,0 +1,18 @@ +/* + * blogc: A blog compiler. + * Copyright (C) 2014-2019 Rafael G. Martins + * + * This program can be distributed under the terms of the BSD License. + * See the file LICENSE. + */ + +#ifndef _SORT_H +#define _SORT_H + +#include "utils.h" + +typedef int (*bc_sort_func_t) (const void *a, const void *b); + +bc_slist_t* bc_slist_sort(bc_slist_t *l, bc_sort_func_t cmp); + +#endif /* _SORT_H */ -- cgit v1.2.3-18-g5258