トップページ > キーワード検索 > bsearch()
C言語規格
C言語(その他)
プログラム
その他
bsearch()
機能 バイナリサーチ(二分探索)で検索を行なう。
定義 #include <stdlib.h>

void * bsearch(
  const void * key,
  const void * base,
  size_t nmemb,
  size_t size,
  int (*compar)( const void *, const void *)
);
引数
key検索するキーワードへのポインタ
base検索対象のオブジェクト配列へのポインタ
nmemb検索対象のオブジェクトの個数
size検索対象のオブジェクトのサイズ
compar比較関数。この関数の戻り値により個々の比較を行う
戻り値 配列中の一致する要素へのポインタを返す。
一致する要素が無い場合は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





inserted by FC2 system