---
name: "SDL_bsearch"
section: "3"
platform: "linux"
package: "libsdl3-doc"
version: "3.2.10+ds-1"
release: "Debian 13 (Trixie)"
platforms: ["linux"]
url: "https://new.carta.tech/SDL_bsearch"
---

# SDL\_bsearch(3)

Perform a binary search on a previously sorted array.

## NAME

SDL\_bsearch - Perform a binary search on a previously sorted array.

## HEADER FILE

Defined in SDL3/SDL\_stdinc.h

## SYNOPSIS

```
#include "SDL3/SDL.h"
```

**void \* SDL\_bsearch(const void \*key, const void \*base, size\_t nmemb, size\_t size, SDL\_CompareCallback compare);**

## DESCRIPTION

For example:

-

  ```
  typedef struct {
      int key;
      const char *string;
  } data;
  int SDLCALL compare(const void *a, const void *b)
  {
      const data *A = (const data *)a;
      const data *B = (const data *)b;
      if (A->n < B->n) {
          return -1;
      } else if (B->n < A->n) {
          return 1;
      } else {
          return 0;
      }
  }
  data values[] = {
      { 1, "first" }, { 2, "second" }, { 3, "third" }
  };
  data key = { 2, NULL };
  data *result = SDL_bsearch(&key, values, SDL_arraysize(values), sizeof(values[0]), compare);
  ```

## FUNCTION PARAMETERS

- *key*

  a pointer to a key equal to the element being searched for.

- *base*

  a pointer to the start of the array.

- *nmemb*

  the number of elements in the array.

- *size*

  the size of the elements in the array.

- *compare*

  a function used to compare elements in the array.

## RETURN VALUE

Returns a pointer to the matching element in the array, or NULL if not found.

## THREAD SAFETY

It is safe to call this function from any thread.

## AVAILABILITY

This function is available since SDL 3.2.0.

## SEE ALSO

**•**(3), [**SDL\_bsearch\_r**(3)](/SDL_bsearch_r/3.md), **•**(3), [**SDL\_qsort**(3)](/SDL_qsort/3.md)
