From adbcf69ed50ea3896d4bbe863ea5d214ae5a0299 Mon Sep 17 00:00:00 2001 From: Charles Date: Thu, 13 Feb 2020 23:15:16 +0100 Subject: Added tests for algo*, fixing ft_bsearch and ft_mergesort --- src/algo/ft_bsearch.c | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) (limited to 'src/algo/ft_bsearch.c') diff --git a/src/algo/ft_bsearch.c b/src/algo/ft_bsearch.c index 8066479..5132fa2 100644 --- a/src/algo/ft_bsearch.c +++ b/src/algo/ft_bsearch.c @@ -6,7 +6,7 @@ /* By: cacharle +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/10 05:29:05 by cacharle #+# #+# */ -/* Updated: 2020/02/10 05:43:18 by cacharle ### ########.fr */ +/* Updated: 2020/02/13 23:14:48 by cacharle ### ########.fr */ /* */ /* ************************************************************************** */ @@ -15,14 +15,18 @@ void *ft_bsearch(const void *base, size_t nel, size_t width, t_ftsearch_const *consts) { - void *found; + int res; + size_t mid; - if ((consts->compar)(consts->key, base + (nel / 2) * width) == 0) - return ((void*)base + (nel / 2) * width); - if ((found = ft_bsearch(base, nel / 2, width, consts)) != NULL) - return (found); - if ((found = ft_bsearch(base + (nel / 2) * width, nel - nel / 2, - width, consts)) != NULL) - return (found); - return (NULL); + if (nel < 1) + return (NULL); + mid = nel / 2; + res = (consts->compar)(consts->key, base + mid * width); + if (res == 0) + return ((void*)base + mid * width); + if (res < 0) + return (ft_bsearch(base, mid, width, consts)); + else + return (ft_bsearch(base + (mid + 1) * width, nel - mid - 1, + width, consts)); } -- cgit