Find operation with bsearch () in C language

Source: Internet
Author: User

The bsearch () can be used in the C language for binary search. As with Qsort (), bsearch () is also included in the library, and the comparison sub-function is also customized. The prototype is as follows:

void *bsearch (const void *key, const void *base, size_t nmem, size_t size, int (*comp) (const void *, const void *));

Header files: #include <stdlib.h>

Key points to the element you are looking for, base points to the array you are looking for, Nmem is a lookup length, typically an array length, size is the number of bytes per element, usually with sizeof (...). Representation, Comp points to the comparison sub-function, which defines the rules for comparison. It is important to note that the data must be pre-ordered, and the rules for sorting are the same as comp points to the comparison sub-function. If the lookup succeeds, the address of the matching element in the array is returned, and the inverse returns NULL. For cases where more than one element matches successfully, bsearch () does not define which one to return.

Cases:

#include <stdio.h>#include <stdlib.h> #define NUM 8int Compare (const void *p, const void *q) {    Return (* (int *) P-* (int *) q);} int main (int argc, char *argv[]) {    int array[num] = {9, 2, 7, one, 3,, 6};    int key = 3; int *p; qsort (array, num, sizeof (int), compare), p = (int *) bsearch (&key, array, num, sizeof (int), compare); (p = = NULL)? Puts ("Not found"): Puts ("found"); return 0;}          

The results are as follows: Found

Find operation with bsearch () in C language

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.