C/Data Structure Algorithm/Search — различия между версиями
Admin (обсуждение | вклад) м (1 версия: Импорт контента...) |
|
(нет различий)
|
Версия 14:20, 25 мая 2010
Binary search:bsearch in stdlib.h
#include <stdio.h>
#include <stdlib.h>
int values[] = { 1 , 2 , 3, 4 , 9 , 10 };
int compare (const void * a, const void * b) {
return ( *(int*)a - *(int*)b );
}
int main ()
{
int *pos;
int key = 9;
pos = (int*) bsearch (&key, values, 6, sizeof (int), compare);
if ( pos != NULL )
printf ("%d is in the array", *pos);
else
printf ("%d is not in the array", key);
return 0;
}
The Binary search
int binary_search(char *items, int count, char key)
{
int low, high, mid;
low = 0; high = count-1;
while(low <= high) {
mid = (low+high)/2;
if(key < items[mid]) high = mid-1;
else if(key > items[mid]) low = mid+1;
else return mid; /* found */
}
return -1;
}