機能 |
バイナリサーチ(二分探索)で検索を行なう。 |
||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
定義 |
#include <stdlib.h> void * bsearch( const void * key, const void * base, size_t nmemb, size_t size, int (*compar)( const void *, const void *) ); |
||||||||||
引数 |
|
||||||||||
戻り値 |
配列中の一致する要素へのポインタを返す。 一致する要素が無い場合はNULLを返す。 |
||||||||||
実装例 |
#include <stdlib.h> #include <stdio.h> /* 比較関数 */ int compare(const void *a, const void *b) { int an = *(int*)(a); int bn = *(int*)(b); if (an < bn) { printf("%d .. %d = Smaller\n", an, bn); return -1; } else if (an > bn) { printf("%d .. %d = Bigger\n", an, bn); return +1; } else { printf("%d .. %d = Equal\n", an, bn); return 0; } } int main(void) { int list[10] = {12, 67, 87, 90, 125, 153, 214, 234, 653, 804}; int key = 90; int *result; /* 検索 */ result = bsearch(&key, list, 10, sizeof(int), compare); /* 結果を表示 */ if (NULL != result) { printf("result=%d\n", *result); } else { printf("result=Not found.\n"); } return 0; } |
||||||||||
実行結果 |
90 .. 125 = Smaller 90 .. 67 = Bigger 90 .. 87 = Bigger 90 .. 90 = Equal result=90 |
bsearch()