From a8686334b2c0806aff9d5088a0a2b1ae7e7cd634 Mon Sep 17 00:00:00 2001 From: Bruce Cowan <bruce@bcowan.me.uk> Date: Thu, 26 Dec 2019 14:32:17 +0000 Subject: [PATCH] Add a binary search which uses the standard library --- src/binary2.c | 42 ++++++++++++++++++++++++++++++++++++++++++ src/meson.build | 1 + 2 files changed, 43 insertions(+) create mode 100644 src/binary2.c diff --git a/src/binary2.c b/src/binary2.c new file mode 100644 index 0000000..0a8189a --- /dev/null +++ b/src/binary2.c @@ -0,0 +1,42 @@ +#include <stdio.h> +#include <stdlib.h> + +#include "utils.h" + +static int list[] = { 8, 11, 17, 22, 29, 38, 51, 58, 65, 67, 74, 81, 87, 90, 96, 97 }; + +#define N_ELEMENTS(arr) (sizeof(arr) / sizeof(arr[0])) + +static int +int_compare (const void *a, const void *b) +{ + static int passes; + + int first = *((int *) a); + int second = *((int *) b); + + passes++; + printf ("\n----------Pass #%d----------\n", passes); + printf ("Comparing %d and %d\n", first, second); + int ret = first - second; + + if (ret < 0) + printf ("%d < %d\n", first, second); + else if (ret > 0) + printf ("%d > %d\n", first, second); + else + printf ("%d == %d\n", first, second); + + return ret; +} + +int +main (int argc, char **argv) +{ + int *vals = get_ints (argc, argv, 1, "What is the number to search for?"); + int key = vals[0]; + + bsearch (&key, list, N_ELEMENTS (list), sizeof (int), int_compare); + + return 0; +} diff --git a/src/meson.build b/src/meson.build index 8d6a535..46eeab5 100644 --- a/src/meson.build +++ b/src/meson.build @@ -2,6 +2,7 @@ executable('add', 'add.c', dependencies: utils_dep) executable('angle', 'angle.c', dependencies: libm) executable('array-length', 'array-length.c', dependencies: types_dep) executable('binary', 'binary.c') +executable('binary2', 'binary2.c', dependencies: utils_dep) executable('complex', 'complex.c', dependencies: libm) executable('doubles', 'doubles.c') executable('einstein', 'einstein.c') -- GitLab