1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
#include <stdio.h>
/* binsearch: find x in v[0] <= v[1] <= ... <= v[n-1] */
int binsearch(int x, int v[], int n) {
int low, mid, high;
low = 0;
high = n - 1;
while ( low <= high ) {
mid = (low+high) / 2;
if ( x < v[mid] )
high = mid - 1;
else if ( x > v[mid] )
low = mid + 1;
else
return mid;
}
return -1;
}
/* Improved version */
int binsearch2(int x, int v[], int n)
{
int low, high, mid;
low = 0;
high = n-1;
while (low <= high) {
mid = (low + high) / 2;
if (x < v[mid])
high = mid-1;
else
low = mid+1;
}
return x == v[mid] ? mid : -1;
}
int main(int argc, char *argv[])
{
unsigned index;
int n = 10; /* Element to search for */
int Array[] = { 2, 4, 6, 8, 10, 12, 14 };
for (index = 0; index < sizeof(Array); index++)
{
int answer = binsearch2( n, Array, sizeof(Array) / sizeof(int) );
printf("%d", answer);
}
}
|