Add a bsearch for list

This commit is contained in:
Nicolas Cornu 2016-10-18 10:37:56 +02:00
parent 2dcb54c32a
commit 51d7091874
2 changed files with 22 additions and 0 deletions

View file

@ -129,3 +129,18 @@ void list_stable_sort(list_t *list, int compare(const void *a, const void *b)) {
list_inplace_sort(list, 0, list->length - 1, compare); list_inplace_sort(list, 0, list->length - 1, compare);
} }
} }
void *list_bsearch(list_t *list, int compare(const void *a, const void *b), const void *data) {
return bsearch(data, list->items, list->length, sizeof(void*), compare);
}
int list_binary_find(list_t *list, int compare(const void *item, const void *data), const void *data, size_t size) {
if (list->length == 0) {
return -1;
}
void **item = list_bsearch(list, compare, data);
if (item != NULL)
return (item-list->items) / size;
else
return -1;
}

View file

@ -1,6 +1,8 @@
#ifndef _SWAY_LIST_H #ifndef _SWAY_LIST_H
#define _SWAY_LIST_H #define _SWAY_LIST_H
#include <stddef.h>
typedef struct { typedef struct {
int capacity; int capacity;
int length; int length;
@ -22,4 +24,9 @@ void list_qsort(list_t *list, int compare(const void *left, const void *right));
int list_seq_find(list_t *list, int compare(const void *item, const void *cmp_to), const void *cmp_to); int list_seq_find(list_t *list, int compare(const void *item, const void *cmp_to), const void *cmp_to);
// stable sort since qsort is not guaranteed to be stable // stable sort since qsort is not guaranteed to be stable
void list_stable_sort(list_t *list, int compare(const void *a, const void *b)); void list_stable_sort(list_t *list, int compare(const void *a, const void *b));
// binary search
void *list_bsearch(list_t *list, int compare(const void *a, const void *data), const void *data);
// Return index for an item that returns 0 for given compare
// function or -1 if none matches.
int list_binary_find(list_t *list, int compare(const void *item, const void *data), const void *data, size_t size);
#endif #endif