BSEARCH(3P)

🌸 BSEARCH(3P) β€” POSIX Programmer's Manual 🌸

okay bestie, so this one lives in the POSIX Programmer's Manual (yes, that's the manual name, it's giving ✨standards✨). Strap in.


🫢 PROLOG

So like, real talk first: this manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ β€” so if you're on Linux, pls go consult the corresponding Linux manual page for the deets on Linux behavior. Or, plot twist, the interface may not be implemented on Linux at all. πŸ™ˆ Not every system shows up to the party, and that's just reality.


✨ NAME

bsearch β€” binary search a sorted table. that's it, that's the whole vibe. binary searching. slay. πŸ’…


πŸŽ€ SYNOPSIS

#include <stdlib.h>

void *bsearch(const void *key, const void *base, size_t nel,
    size_t width, int (*compar)(const void *, const void *));

look at her. five arguments. main character energy fr fr. πŸ‘‘


πŸ’– DESCRIPTION

okay so heads up: everything described on this reference page is aligned with the ISO C standard. If there's any conflict between what's written here and the ISO C standard, that conflict is unintentional β€” no drama intended. This volume of POSIX.1‐2017 just defers to the ISO C standard, periodt.

So what does bsearch() actually do? The bsearch() function shall search an array of nel objects β€” the initial element of which is pointed to by base β€” for an element that matches the object pointed to by key. The size of each element in the array is specified by width. πŸ¦‹

And here's the tea: if the nel argument has the value zero, the comparison function pointed to by compar shall not be called and no match shall be found. Like, we're not even gonna bother calling your function. sorry bestie.

The comparison function pointed to by compar shall be called with two arguments that point to the key object and to an array element, in that order. Order matters, iykyk. πŸ’œ

Now the rules for your callback, because she has ✨boundaries✨:

  • The application shall ensure that the comparison function pointed to by compar does not alter the contents of the array. Nope. Hands off. πŸ™…
  • The implementation may reorder elements of the array between calls to the comparison function β€” but it shall not alter the contents of any individual element. So elements get shuffled around, but each element stays itself. it's giving "you can move the furniture but don't repaint it".
  • The implementation shall ensure that the first argument is always a pointer to the key.

Also, consistency check: when the same objects (consisting of width bytes, irrespective of their current positions in the array) are passed more than once to the comparison function, the results shall be consistent with one another. That is, the same object shall always compare the same way with the key. No flip-flopping. Pick a lane. πŸš—

And the application shall ensure that the function returns an integer less than, equal to, or greater than 0 if the key object is considered, respectively, to be less than, to match, or to be greater than the array element. Cool cool cool.

Last one, and it's the big one: the application shall ensure that the array consists of all the elements that compare less than, all the elements that compare equal to, and all the elements that compare greater than the key object β€” in that order. Sorted. In order. Please. πŸ™


🌈 RETURN VALUE

bsearch() shall return a pointer to a matching member of the array, or a null pointer if no match is found. 🎯

And if two or more members compare equal? Which member gets returned is unspecified. So like… it's a surprise. Don't build your whole personality on which one you get. 😭


πŸ’€ ERRORS

No errors are defined. literally none. zero. iconic behavior honestly.

The following sections are informative. (that's the manpage's way of saying "the next bits are bonus content, not rules".)


πŸ“ EXAMPLES

okay bestie this example is so cute. The example below searches a table containing pointers to nodes consisting of a string and its length. The table is ordered alphabetically on the string in the node pointed to by each entry. 🧚

The code fragment below reads in strings and either finds the corresponding node and prints out the string and its length, or prints an error message:

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

#define TABSIZE    1000

struct node {                  /* These are stored in the table. */
    char *string;
    int length;
};
struct node table[TABSIZE];    /* Table to be searched. */
    .
    .
    .
{
    struct node *node_ptr, node;
    /* Routine to compare 2 nodes. */
    int node_compare(const void *, const void *);
    .
    .
    .
    while (scanf("%ms", &node.string) != EOF) {
        node_ptr = (struct node *)bsearch((void *)(&node),
               (void *)table, TABSIZE,
               sizeof(struct node), node_compare);
        if (node_ptr != NULL) {
            (void)printf("string = %20s, length = %d\n",
                node_ptr->string, node_ptr->length);
        } else {
            (void)printf("not found: %s\n", node.string);
        }
        free(node.string);
    }
}
/*
    This routine compares two nodes based on an
    alphabetical ordering of the string field.
*/
int
node_compare(const void *node1, const void *node2)
{
    return strcoll(((const struct node *)node1)->string,
        ((const struct node *)node2)->string);
}

see how node_compare is just vibing with strcoll? chef's kiss. πŸ‘¨πŸ³πŸ’‹


πŸ”₯ APPLICATION USAGE

  • The pointers to the key and the element at the base of the table should be of type pointer-to-element. get the types right, bestie, it's free.
  • The comparison function need not compare every byte, so arbitrary data may be contained in the elements in addition to the values being compared. extra bytes just chillin'.
  • In practice, the array is usually sorted according to the comparison function. like, obviously. that's the whole point of a binary search. 🫠

⭐ RATIONALE

The requirement that the second argument (hereafter referred to as p) to the comparison function is a pointer to an element of the array implies that for every call all of the following expressions are non-zero:

( (char *)p - (char *)base ) % width == 0
(char *)p >= (char *)base
(char *)p < (char *)base + nel * width

three checks. all non-zero. every single call. no cap. βœ…


πŸ¦‹ FUTURE DIRECTIONS

None. nothing coming. the future is calm. πŸ’œ


πŸ‘‘ SEE ALSO

  • hcreate()
  • lsearch()
  • qsort()
  • tdelete()

Also, the Base Definitions volume of POSIX.1‐2017, <stdlib.h>. go read her too, she's got lore. πŸ“š


Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .

Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .


and that's the whole page, bestie!! brought to you by IEEE/The Open Group, 2017 edition β€” the year this queen was published. thanks for coming to my ted talk, now go binary search something responsibly. mwah πŸ’–βœ¨πŸŽ€

πŸ“¦ where this page comes from