Skip to content
Snippets Groups Projects
Commit a8686334 authored by Bruce Cowan's avatar Bruce Cowan :airplane:
Browse files

Add a binary search which uses the standard library

parent 1a088a4b
No related branches found
No related tags found
No related merge requests found
#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;
}
......@@ -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')
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment