📄 bsearch.c
字号:
/* * bsearch.c * Original Author: G. Haley * * Searches an array of nmemb members, the initial member of which is pointed * to by base, for a member that matches the object pointed to by key. The * contents of the array shall be in ascending order according to a comparison * function pointed to by compar. The function shall return an integer less * than, equal to or greater than zero if the first argument is considered to be * respectively less than, equal to or greater than the second. Returns a * pointer to the matching member of the array, or a null pointer if no match * is found. *//*FUNCTION<<bsearch>>---binary searchINDEX bsearchANSI_SYNOPSIS #include <stdlib.h> void *bsearch(const void *<[key]>, const void *<[base]>, size_t <[nmemb]>, size_t <[size]>, int (*<[compar]>)(const void *, const void *));TRAD_SYNOPSIS #include <stdlib.h> char *bsearch(<[key]>, <[base]>, <[nmemb]>, <[size]>, <[compar]>) char *<[key]>; char *<[base]>; size_t <[nmemb]>, <[size]>; int (*<[compar]>)();DESCRIPTION<<bsearch>> searches an array beginning at <[base]> for any elementthat matches <[key]>, using binary search. <[nmemb]> is the elementcount of the array; <[size]> is the size of each element.The array must be sorted in ascending order with respect to thecomparison function <[compar]> (which you supply as the last argument of<<bsearch>>).You must define the comparison function <<(*<[compar]>)>> to have twoarguments; its result must be negative if the first argument isless than the second, zero if the two arguments match, andpositive if the first argument is greater than the second (where``less than'' and ``greater than'' refer to whatever arbitraryordering is appropriate).RETURNSReturns a pointer to an element of <[array]> that matches <[key]>. Ifmore than one matching element is available, the result may point toany of them.PORTABILITY<<bsearch>> is ANSI.No supporting OS subroutines are required.*/#include <stdlib.h>_PTR_DEFUN (bsearch, (key, base, nmemb, size, compar), _CONST _PTR key _AND _CONST _PTR base _AND size_t nmemb _AND size_t size _AND int _EXFUN ((*compar), (const _PTR, const _PTR))){ _PTR current; int result; if (nmemb == 0 || size == 0) return NULL; while (nmemb) { current = (_PTR) (((char *) base) + ((nmemb / 2) * size)); result = compar (key, current); if (result < 0) nmemb /= 2; else if (result > 0) { base = (_PTR) (((char *) current) + size); nmemb = (nmemb / 2) - (nmemb % 2 ? 0 : 1); } else return current; } if (compar (key, base) == 0) return (_PTR) base; return NULL;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -