C++二分检索例子

来源:百度知道 编辑:UC知道 时间:2024/05/07 20:43:36
求一个二分检索例子

写点注释
谢谢

#include <stdlib.h>
#include <stdio.h>

typedef int (*fptr)(const void*, const void*);

#define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))

int numarray[] = {123, 145, 512, 627, 800, 933};

int numeric (const int *p1, const int *p2)
{
return(*p1 - *p2);
}

#pragma argsused
int lookup(int key)
{
int *itemptr;

/* The cast of (int(*)(const void *,const void*))
is needed to avoid a type mismatch error at
compile time */
itemptr = (int *) bsearch (&key, numarray, NELEMS(numarray),
sizeof(int), (fptr)numeric);
return (itemptr !=