函式名: bsearch
功 能: 二分法搜尋
基本介紹
- 中文名: bsearch
- 功 能: 二分法搜尋
- 用 法: void *bsearch
- 類型:函式名
簡介,程式例,
簡介
用 法: void *bsearch(const void *key, const void *base, size_t nelem, size_t width, int(*fcmp)(const void *, const void *));
語法:
#include <stdlib.h> void *bsearch( const void *key, const void *buf, size_t num, size_t size, int (*compare)(const void *, const void *) );
功能: 函式用折半查找法在從數組元素buf[0]到buf[num-1] 匹配參數key。如果函式compare 的第一個參數小於第二個參數,返回負值;如果等於返回零值;如果大於返回正值。數組buf 中的元素應以升序排列。函式bsearch()的返回值是指向匹配項,如果沒有發現匹配項,返回NULL
程式例
程式例:
#include<stdlib.h>#include<stdio.h>#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);}int lookup(int key){int *itemptr;// The cast of (int(*)(const void *,const void*)) is needed to avoid a type mismatch error at compile timeitemptr = (int *)bsearch (&key, numarray, NELEMS(numarray),sizeof(int), (int(*)(const void *,const void *))numeric);return (itemptr != NULL);}int main(void){if (lookup(512)){printf("512 is in the table.\n");}else{printf("512 isn't in the table.\n");}return 0;}
例2:
#include <stdlib.h>#include <stdio.h>#include <string.h>#define LENGTH(x) sizeof(x)/sizeof(x[0])/**輸出數組元素*\param arr:指向數組的指針*\param len:數組元素的個數*/void print(char (*arr)[10],int len){int i;for (i=0;i<len;i++){printf("%s ",arr[i]);}printf("\n");}int main(){char arr[][10]={"bac","bca","abc","acb","cba","cab"}; /* 定義二維字元數組*/char *key="bca";/* 要查找的字元串*/char *ptr=NULL; /* 字元指針*/// 輸出未排序時字元數組的內容printf("before qsort :");print(arr,LENGTH(arr));/* 使用qsort對字元數組排序*/qsort((void *)arr,LENGTH(arr),sizeof(arr[0]),(int (*)(const void *,const void *))strcmp);/* 輸出排序後字元數組的內容*/printf("after qsort :");print(arr,LENGTH(arr));/* 採用二分查找查找指定字元*/ptr=(char *)bsearch(key,arr,LENGTH(arr),sizeof(arr[0]),(int (*)(const void *,const void *))strcmp);if (ptr){ /* 找到*/printf("%s is in the array\n",key);}else/* 沒找到*/{printf("%s isn't in the array\n",key);}return 0;}