Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C library function - bsearch()

C library function - bsearch()

C Standard Library - <stdlib.h> C Standard Library -

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

Return Value

Comparison function

The comparison function must conform to the following signature:



int compar(const void *a, const void *b);

The function returns:

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 - <stdlib.h> C Standard Library -