aboutsummaryrefslogtreecommitdiff
path: root/src/algo/ft_bsearch.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/algo/ft_bsearch.c')
-rw-r--r--src/algo/ft_bsearch.c24
1 files changed, 14 insertions, 10 deletions
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 <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* 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));
}