You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
1.8 KiB
C

/*
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 <limits.h>
#include <stdio.h>
#include <assert.h>
#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;
} else 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);
}