bsearch : bsearch « stdlib.h « C Tutorial

Home
C Tutorial
1.Language
2.Data Type
3.String
4.printf scanf
5.Operator
6.Statement
7.Array
8.Function
9.Structure
10.Pointer
11.Memory
12.Preprocessor
13.File
14.Data Structure
15.Search Sort
16.Wide Character String
17.assert.h
18.ctype.h
19.math.h
20.setjmp.h
21.signal.h
22.stdio.h
23.stdlib.h
24.string.h
25.time.h
26.wctype.h
C / ANSI-C
C++
C++ Tutorial
Visual C++ .NET
C Tutorial » stdlib.h » bsearch 
23.8.1.bsearch
ItemValue
Header filestdlib.h
Declarationvoid *bsearch(const void *key, const void *buf, size_t num, size_t size, int (*compare)(const void *, const void *));
Functionperforms a binary search on the sorted array *buf
Returnreturns a pointer to the first member that matches *key. If the array does not contain the key, a null pointer is returned.
ParameterThe array must be sorted in ascending order. The number of elements in the array is specified by num, and the size (in bytes) of each element is described by size.


The function pointed to by compare is used to compare an element of the array with the key.

The form of the compare function must be as follows:

int func_name(const void *arg1, const void *arg2);

It must return values as described in the following table:

ComparisonValue Returned
arg1 < arg2< 0
arg1 == arg20
arg1 > arg2> 0


#include <stdlib.h>
  #include <ctype.h>
  #include <stdio.h>

  char *alpha = "abcdefghijklmnopqrstuvwxyz";

  int comp(const void *ch, const void *s);

  int main(void)
  {
    char ch;
    char *p;

    printf("Enter a character: ");
    ch = getchar();
    ch = tolower(ch);
    p = (char *bsearch(&ch, alpha, 261, comp);
    if(pprintf(" %c is in alphabet\n", *p);
    else printf("is not in alphabet\n");

    return 0;
  }

  /* Compare two characters. */
  int comp(const void *ch, const void *s)
  {
    return *(char *)ch - *(char *)s;
  }
23.8.bsearch
23.8.1.bsearch
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.