Table of Contents
This guide covers the function bsearch ()() in c with practical context and easy-to-follow details. Use it to understand the subject and apply the information confidently.
The Function Bsearch ()() in C
The contents of the array should be in ascending order corresponding to the comparison function referenced by compar.
The bsearch () function, which stands for Binary Search, is based on the idea of Binary Search algorithm (Binary Search), you can refer to this algorithm in Binary Search Algorithm.
Declare the Function Bsearch ()() in C
Below is the declaration for bsearch () in C:
void * bsearch ( const void * key , const void * base , size_t nitems , size_t size , int (* compar )( const void *, const void *))
Parameters
Key : This is the pointer to an object that acts as a key to search, is cast as a void *.
Base : This is the pointer to the first object of the array, where the search is performed, cast in the form of a void *.
Nitems : This is the number of elements in the array pointed to by the base.
Size : This is the size (byte value) of each element in the array.
Compare : This is a function to compare two elements.
Returns the Value
This function returns a pointer to an entry in the array that connects to the search key. If the key is not found, the function returns a NULL pointer.
For Example
The following C program illustrates the usage of bsearch () in C:
#include #include int cmpfunc ( const void * a , const void * b ) { return ( *( int *) a - *( int *) b ); } int values [] = { 5 , 20 , 29 , 32 , 63 }; int main () { int * item ; int key = 32 ; /* su dung ham bsearch() de tim gia tri 32 trong mang */ item = ( int *) bsearch (& key , values , 5 , sizeof ( int ), cmpfunc ); if ( item != NULL ) { printf ( "Da tim thay phan tu co gia tri = %dn" , * item ); } else { printf ( "Khong tim thay phan tu co gia tri = %dn" , * item ); } return ( 0 ); } Compiling and running the above C program will result:
According to Tutorialspoint
Previous lesson: Function system () in C
Next lesson: qsort () function in C
Frequently Asked Questions
What should I check before following these steps?
Confirm device and software compatibility, save important data, and make sure you have the required permissions, files, and account access.
Why might the process not work?
Common causes include outdated software, missing permissions, incompatible hardware, an unstable connection, or completing a step in the wrong order.
Can I undo the changes if necessary?
That depends on the tool or setting. Use built-in restore options when available, keep a backup, and record the original configuration first.
Was this article helpful?
Your feedback helps us improve.
Reader Comments 0
Sign in with email or Google to join the discussion.