C library function - bsearch()
bsearch is a function in the C standard library used to perform a binary search on a sorted array; it is defined in the stdlib.h header file.
C library function **void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void , const void )) locks nitems performs a binary search on an array of objects,base points to the array to be searched,key points to the element to be found,size specifies the size of each element in the array.
The contents of the array should be sorted in ascending order according to compar the corresponding comparison function.
Declaration
The following is the declaration of the bsearch() function.
void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
Parameters
key: Pointer to the target element to be found.base: Pointer to the start position of the array.nmemb: Number of elements in the array.size: Size of each element (in bytes).compar: Pointer to a comparison function used to compare two elements.
Return Value
- If a matching element is found,
bsearchreturns a pointer to that element. - If no matching element is found,
bsearchReturnNULL.
Comparison function
The comparison function must conform to the following signature:
int compar(const void *a, const void *b);
The function returns:
- A negative value, if
aLess thanb. - Zero, if
aEqualb. - A positive value, if
aGreater thanb.
Example
The following example demonstrates the use of the bsearch() function.
Example
#include
<
stdio.h
#include
<
stdlib.h// Comparison function used by bsearch for searching
int
cmpfunc
(
const
void
a
,
const
void
b
)
{
return
(
(
int
)
a
(
int
)
b
)
;
}
int
main
(
)
{
int
values
[
]
=
{
5
,
20
,
29
,
32
,
63
}
;
int
key
=
32
;
int
item
;
// Compute the array length
size_t
array_size
=
sizeof
(
values
)
/
sizeof
(
values
[
0
]
)
;
// Use bsearch to find the value 32 in the array
item
=
(
int
)
bsearch
(
&
key
,
values
,
array_size
,
sizeof
(
int
)
,
cmpfunc
)
;
// Check the search result and output it
if
(
item
!=
NULL
)
{
printf
(
"
Found item = %d
\
n
"
, *
item
)
;
}
else
{
printf
(
"
Item = %d could not be found
\
n
"
,
key
)
;
}
return
0
;
}
Let's compile and run the above program, which will produce the following result:
Found item = 32
C Standard Library -