bsearch ()- 搜尋陣列

格式

#include <stdlib.h>
void *bsearch(const void *key, const void *base,
              size_t num, size_t size,
              int (*compare)(const void *key, const void *element));

語言層次

ANSI

安全執行緒

說明

bsearch() 函數會執行 num 元素陣列的二進位搜尋,每一個 size 位元組。 陣列必須依 compare所指向的函數以遞增順序排序。 base 是指向要搜尋之陣列基礎的指標,而 key 是所探查的值。

compare 引數是您必須提供之函數的指標,該函數會比較兩個項目並傳回指定其關係的值。 compare() 函數之引數清單中的第一個項目是指向所搜尋之項目值的指標。 compare() 函數的引數清單中的第二個項目是指向陣列 元素索引鍵相互比較的指標。 compare() 函數必須比較索引鍵值與陣列元素,然後傳回下列其中一個值:
Value 意義
小於 0 key 小於 元素
0 key元素相同
大於 0 key 大於 元素

回覆值

bsearch() 函數會將指標傳回 base 所指向陣列中的 key 。 如果兩個索引鍵相等,則未指定 key 將指向的元素。 如果 bsearch() 函數找不到 key,則會傳回 NULL

範例

此範例會對程式參數的 argv 指標陣列執行二進位搜尋,並尋找引數 PATH的位置。 它會先從 argv中移除程式名稱,然後按字母順序排序陣列,再呼叫 bsearch()compare1()compare2() 函數會比較 arg1arg2 所指向的值,並將結果傳回 bsearch() 函數。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
 
int compare1(const void *, const void *);
int compare2(const void *, const void *);
 
main(int argc, char *argv[])
{                        /* This program performs a binary        */
  char **result;         /* search on the argv array of pointers  */
  char *key = "PATH";    /* to the program parameters.  It first  */
  int i;                 /* removes the program name from argv    */
                         /* then sorts the array alphabetically   */
  argv++;                /* before calling bsearch.               */
  argc--;
 
  qsort((char *)argv, argc, sizeof(char *), compare1);
 
  result = (char**)bsearch(&key, (char *)argv, argc, sizeof(char *), compare2);
  if (result != NULL)  {
      printf("result =<%s>\n",*result);
   }
  else printf("result is null\n");
}
 
         /*This function compares the values pointed to by arg1  */
         /*and arg2 and returns the result to qsort.  arg1 and   */
         /*arg2 are both pointers to elements of the argv array. */
 
int compare1(const void *arg1, const void *arg2)
{
    return (strcmp(*(char **)arg1, *(char **)arg2));
}
 
         /*This function compares the values pointed to by arg1  */
         /*and arg2 and returns the result to bsearch            */
         /*arg1 is a pointer to the key value, arg2 points to    */
         /*the element of argv that is being compared to the key */
         /*value.                                                */
 
int compare2(const void *arg1, const void *arg2)
{
    return (strcmp(*(char **)arg1, *(char **)arg2));
}
/********************  Output should be similar to:  *************
 
result = <PATH>
 
****************** When the input on the command line is ********
 
CALL BSEARCH PARM(WHERE IS PATH IN THIS PHRASE'?')
 
*/

相關資訊