diff --git a/.gitignore b/.gitignore index 7f74da5..de40e4f 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,4 @@ multibrot.png bloom wo-lernen lua-foo +binsearch diff --git a/Makefile b/Makefile index 6be883f..fada90b 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ CFLAGS=-std=c99 -Wall -g -O2 INDENTOPTS=-kr --no-tabs --braces-on-func-def-line --indent-level2 -TARGETS=approximate-pi linked-list mandelbrot threads circular-buffer structs ncurses-pong bit-fuckery bit-fuckery2 checkcheck multibrot bloom wo-lernen lua-foo +TARGETS=approximate-pi linked-list mandelbrot threads circular-buffer structs ncurses-pong bit-fuckery bit-fuckery2 checkcheck multibrot bloom wo-lernen lua-foo binsearch EXTRAS=mandelbrot.bmp multibrot.png .PHONY: all diff --git a/binsearch.c b/binsearch.c new file mode 100644 index 0000000..b00f2db --- /dev/null +++ b/binsearch.c @@ -0,0 +1,80 @@ +/* +Write a recursive function that searches for a target in a sorted array using +binay search, where the array, its size and the target are given as parameters. +*/ + +#include +#include +#include + +#define DEBUG 1 +#define debug_printf(fmt, ...) \ + do { if (DEBUG) fprintf(stderr, fmt, __VA_ARGS__); } while (0) + +void assert_sorted(int array[], int arraylen) { + int n = INT_MIN; + + for (int i = 0; i < arraylen; i++) { + assert(n <= array[i]); + n = array[i]; + } +} + +int binsearchr(int array[], int from, int to, int target) { + int m = from + (to-from)/2; + debug_printf("from = %d, to = %d, m = %d\n", from, to, m); + + if (to < from) + return -1; + + if (array[m] == target) { + return m; + } if (array[m] > target) { + return binsearchr(array, from, m-1, target); + } else { + /* array[m] < target */ + return binsearchr(array, m+1, to, target); + } +} + +int binsearch(int array[], int arraylen, int target) { + return binsearchr(array, 0, arraylen-1, target); +} + +int main(void) { + int a[43] = { + 912, 1204, 1761, 2143, 3691, + 5150, 5249, 6864, 6871, 6902, + 9567, 9703, 10411, 10686, 13501, + 14378, 16249, 17393, 17911, 18614, + 19284, 19595, 19960, 20052, 20702, + 21090, 22277, 22624, 24634, 24877, + 25367, 25586, 26706, 26720, 26958, + 27478, 28269, 29142, 30630, 30804, + 31984, 32398, 32588 }; + assert_sorted(a, 43); + + assert(binsearch(a, 43, 912) == 0); + assert(binsearch(a, 43, 3691) == 4); + assert(binsearch(a, 43, 32588) == 42); + assert(binsearch(a, 43, 12345) == -1); + + int b[2] = { 23, 42 }; + assert_sorted(b, 2); + + assert(binsearch(b, 2, 23) == 0); + assert(binsearch(b, 2, 42) == 1); + assert(binsearch(b, 2, 5) == -1); + assert(binsearch(b, 2, 99) == -1); + + int c[1] = { 0 }; + assert_sorted(c, 1); + + assert(binsearch(c, 1, 0) == 0); + assert(binsearch(c, 1, 1) == -1); + + int d[0]; + assert_sorted(d, 1); + + assert(binsearch(d, 0, 0) == -1); +}