Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. C Language Dictionary
  3. qsort() / bsearch()

qsort() / bsearch()

Generic functions for sorting and searching arrays of any type. By passing the comparison logic as a function pointer, they can handle complex data types such as structs.

Syntax

// Sorts an array using the given comparison function (often implemented as quicksort).
// base: pointer to the first element. nmemb: number of elements. size: size of each element in bytes.
// compar: comparison function (returns negative, 0, or positive).
void qsort(void *base, size_t nmemb, size_t size,
           int (*compar)(const void *, const void *));

// Searches a sorted array for key using binary search.
// Returns a pointer to the matching element, or NULL if not found.
void *bsearch(const void *key, const void *base, size_t nmemb, size_t size,
              int (*compar)(const void *, const void *));

Comparison Function Return Values

Return valueMeaningDescription
Negativea < bThe first argument is considered less than the second. It comes first in ascending order.
0a == bThe two elements are considered equal.
Positivea > bThe first argument is considered greater than the second. It comes last in ascending order.

Sample Code

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

// Comparison function for ascending int order.
int cmp_int_asc(const void *a, const void *b) {
    return (*(int *)a - *(int *)b);
}

// Comparison function for descending score order using a struct.
typedef struct { char name[32]; int score; } Player;
int cmp_score_desc(const void *a, const void *b) {
    return ((Player *)b)->score - ((Player *)a)->score;
}

int main(void) {
    // Sort an int array in ascending order.
    int nums[] = {5, 2, 8, 1, 9, 3};
    int n = sizeof(nums) / sizeof(nums[0]);
    qsort(nums, n, sizeof(int), cmp_int_asc);
    printf("Sorted: ");
    for (int i = 0; i < n; i++) printf("%d ", nums[i]);
    printf("\n"); // Outputs: 1 2 3 5 8 9

    // Use bsearch to find a value in the sorted array.
    int key = 5;
    int *found = (int *)bsearch(&key, nums, n, sizeof(int), cmp_int_asc);
    if (found) printf("Found: %d\n", *found); // Outputs: Found: 5
    int key2 = 7;
    if (!bsearch(&key2, nums, n, sizeof(int), cmp_int_asc))
        printf("7 was not found.\n");

    // Sort a struct array by score in descending order.
    Player players[] = {{"Alice", 85}, {"Bob", 92}, {"Carol", 78}};
    int np = sizeof(players) / sizeof(players[0]);
    qsort(players, np, sizeof(Player), cmp_score_desc);
    for (int i = 0; i < np; i++)
        printf("Rank %d: %s (%d pts)\n", i + 1, players[i].name, players[i].score);

    return 0;
}

Notes

Using simple subtraction in a comparison function (e.g., return *(int*)a - *(int*)b) is intuitive, but it can overflow when combining large positive and large negative values. The safe approach is to write if (*a < *b) return -1; if (*a > *b) return 1; return 0;.

bsearch() requires the array to be sorted according to the same comparison function. Using it on an unsorted array produces incorrect results. Always sort the array with qsort() first.

For details on comparison functions for strings, see also strcmp().

If you find any errors or copyright issues, please .