C Standard Libraries C++

bsearch()

Declaration

void* bsearch(  const void* kvpFind,
        const void* kvpArray,
        size_t qNumberOfElements,
        size_t qElementSizeInBytes,
        int (*pfnCompareFn) ( const void *, const void *));

Description

Performs a binary search on a ordered array of unique elements to locate one that is equal to the value at "kvpFind." THe second argument 'kvpArray" is a pointer to the beginning of the array to be searched. The value "qNumberOfElements" is the number of elements in the array. The value "qElementSizeInBytes" is the size of each element of the array. Finally, the function pointer, "pfnCompareFn," is the comparison function for comparing two elements of the array. The comparison function returns an int that is less than 0 if the first argument is smaller, 0 if the arguments are equal, and an int that is greater than zero if the the first argument is larger than the second. The bsearch() function returns a pointer to the element that was found or NULL if the at "kvpFind" is not in the array.

Example

#include <iostream>
#include <cstdlib>

int MyCompare(const void* kvpFirst, const void* kvpSecond) {
    int iFirst      = *((int*)(kvpFirst));
    int iSecond     = *((int*)(kvpSecond));
    if (iFirst < iSecond) {
        return -1;
    } else if (iFirst == iSecond) {
        return 0;
    } else {
        return 1;
    }
}

int main() {
    using namespace std;

    int iaArray[9] = {1, 3, 6, 7, 9, 13, 15, 16, 19};
    int iSeven = 7;
    // Search for the value seven in the array
    void* vpResult = bsearch(&iSeven, iaArray, 9, sizeof(int), MyCompare);
    // Seven is found at the element #3 in the array
    cout << "Found at element #"
         << (((int*)vpResult) - (int*)iaArray) << endl;

    return 0;
}

Output

bsearch() Output
 

© 2007–2024 XoaX.net LLC. All rights reserved.