C2A_Core
bsearch.c
[詳解]
1 
8 #include <stdlib.h>
9 
10 // compare func(key, base[i])
11 // key < b: compr_func(key, b) < 0
12 // key = b: compr_func(key, b) = 0
13 // key > b: compr_func(key, b) > 0
14 typedef int (*compr_func)(const void*, const void*);
15 
16 void *bsearch(const void* key, const void* base, size_t nmemb, size_t size, compr_func compr)
17 {
18  size_t min = 0;
19  size_t max = nmemb;
20 
21  if (nmemb == 0 || size == 0)
22  {
23  return NULL;
24  }
25 
26  while (min < max)
27  {
28  size_t index = (min + max) / 2;
29  void* current = (void*) ((char*)base + (size * index));
30 
31  int result = compr(key, current);
32  if (result == 0)
33  {
34  // found
35  return current;
36  }
37  else if (result < 0)
38  {
39  // key < current
40  max = index;
41  }
42  else // result > 0
43  {
44  // current < key
45  min = index + 1;
46  }
47  }
48 
49  // not found
50  return NULL;
51 }
int(* compr_func)(const void *, const void *)
Definition: bsearch.c:14
void * bsearch(const void *key, const void *base, size_t nmemb, size_t size, compr_func compr)
Definition: bsearch.c:16