i,
If i have an array like {1,4, 10, 15 , 20 , 30 } of size n , now if i
want to search for number
25 , i should get 20 , if i search for number 11 i hould get 10 , if i
search for 4 i should get 4, if i search for a number and it doesn't
exist i should get the lower number between which it lies. All numbers
are bound to lie between 1 and n.
Can you tell me a easy way to do it.
/* BEGIN new.c */
#include <stdio.h>
int comparison(const void *arg1, const void *arg2);
void *HW_search(const void *key, const void *base,
size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
int main (void)
{
int x, *found;
int array[] = {1,4, 10, 15 , 20 , 30 };
int targets[] = {25, 11, 4, 1, 2, 3, 23};
for (x = 0; x != sizeof targets / sizeof *targets; ++x) {
printf("Searching array for %d\n", targets[x]);
found = HW_search(
targets + x,
array,
sizeof array / sizeof *array,
sizeof *array,
comparison);
printf("found %d\n\n", *found);
}
return 0;
}
int comparison(const void *arg1, const void *arg2)
{
return *(int*)arg2 > *(int*)arg1 ? -1
: *(int*)arg2 != *(int*)arg1;
}
void *HW_search(const void *key, const void *base,
size_t nmemb, size_t size,
int (*compar)(const void *, const void *))
{
int comp;
size_t odd_mask, bytes, middle, high, low;
const unsigned char *array, *found;
found = NULL;
if (nmemb != 0) {
odd_mask = size ^ size - 1;
array = base;
low = 0;
high = nmemb * size;
do {
bytes = high - low;
middle = (bytes & odd_mask ? bytes - size : bytes) / 2
+ low;
base = middle + array;
comp = compar(key, base);
if (comp > 0) {
low = middle;
} else {
high = middle;
if (comp == 0) {
found = array + high;
}
}
} while (bytes != size);
}
return (void *)(found == NULL ? array + middle : found);
}
/* END new.c */