VOOZH about

URL: https://www.geeksforgeeks.org/c/bsearch-function-in-c/

⇱ bsearch() Function in C - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

bsearch() Function in C

Last Updated : 15 Apr, 2024

In C programming language, bsearch() function is used to perform a binary search on a sorted array to search for an element. The name bsearch stands for “binary search” which is an efficient algorithm for finding an item from a sorted list of items. It is defined inside the stdlib.h header file.

Syntax of bsearch() in C

void* bsearch(key, base, num, size, compare);

Parameters of bsearch()

The bsearch() function takes five parameters:

  • key: Pointer to the element to search for.
  • base: Pointer to the first element of the array.
  • num: Number of elements in the array.
  • size: Size of each element in an array.
  • compare: Function pointer to a comparison function that compares the matching element.

Return Value of bsearch()

The bsearch() function returns two values:

  • The pointer to the matching element in the array if the key is found.
  • If the key is not found, it returns a NULL pointer.

bsearch() Comparator Function

The comparator function is passed as a parameter to the bsearch() function and it contains the logic to find the matching element. 

Signature of Comparator Function

int comparatorName(const void* ptr1, const void* ptr2);

Here, ptr1 and ptr2 are the pointers to the elements to be compared. All the comparator function should have the same signature.

The comparator function should return the result as:

  • If the first argument is less than the second, return a negative integer.
  • If the first argument is greater than the second, return a positive integer.
  • If the arguments are equal, return zero.

Example of bsearch() in C

The below example demonstrates how we can search an element using bsearch() in C.


Output
3 Found at index 2

Time Complexity: O(log N), where n is the number of elements in the array.
Auxilliary Space: O(1)



Comment