Binary Search
Binary Search
Binary Search
#include <stdio.h>
#include "1_search.h"
int main()
{
int a[] = {10, 15, 25, 30, 40, 45, 60, 70, 75};
int n = 9;
printf("search : %d\n", bsearch(a, 0, n - 1, 30));
printf("search : %d\n", bsearch(a, 0, n - 1, 65));
#ifndef SEARCH_H
#defne SEARCH_H
int bsearch(int a[], int l, int r, int x);
#endif
#include <stdio.h>
#include "1_search.h"
#if 0
int bsearch(int a[], int l, int r, int x)
{
int m;
int pos = -1;
// when the element could still exist and is not found do
while(l <= r && pos == -1)
{
m = (l + r) / 2;
if(a[m] == x)
{
pos = m;
}
else if(a[m] > x)
{
r = m - 1;
}
else
{
l = m + 1;
}
}
return pos;
}
#endif
This next example shows binary search on an array of structures ordered based
on some key and search is based on a predicate.
Observe the changes in the bsearch function from 1_event_array.c.
This parameter compare is used to compare the given element with the
element in position m. This comparison decides whether the element is found
or which portion of the array should be discarded.
#include <stdio.h>
#include "1_struct.h"
#include "1_struct.h"
#include "1_event.h"
#include "1_event_array.h"
#include <string.h>
event_t e;
printf("reading event : ");
read_event(&e);
disp_event(&e);
read_event(&e);
res = bsearch(events, 0, n - 1, e, compare_detail);
printf("res : %d\n", res);
}
What should binary search return if the element is not found? We returned -1.
Can we return an indication where it would have been if the element were
found? Make the result to indicate that the element is not found. Make the
magnitude such that it gives the position where the element would have been
found. Think about it.