qsort() and bsearch() Functions in C

This C Tutorial explains qsort() and bsearch() functions in C with examples.

‘qsort()’ function is used to sort an array of values in ascending order. This function is defined in ‘stdlib.h’ header and is prototyped as below

void qsort(void *array, size_t no_of_elements, size_t size_of_element,
int (*compare)(void const *, void const *));

Notice that first argument is array to be sorted, second argument specifies no. of elements in the array, third is size of element (in characters) and last argument is pointer-to-function that compares elements. Note further that ‘compare()’ function takes two arguments of type ‘void const *’, therefore cast the valuse to proper type. ‘compare()’ function returns integer value less than, equal to and greater than if fist value is smaller, equal to or larger than second value. Let’s consider a C program that reads in strings, calls ‘qsort()’ to sort an array of strings.

/* qsort.c -- program calls qsort() to sort an array of strings */
/* in ascending order */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#define NOSTRINGS 5
#define SIZE 26
 
int string_compare(void const *, void const *);
 
int main(void)
{
    int i;
    char strings[NOSTRINGS][SIZE];
 
    /* read strings from the user */
    printf("User, write in %d character strings...\n", NOSTRINGS);
    for (i= 0; i < NOSTRINGS; i++)
        fgets(strings[i], SIZE, stdin);
 
    /* display array of unsorted strings */
    printf("Before Sorting:\n");
    for (i = 0; i < NOSTRINGS; i++)
        fputs(strv style="text-align:justify">
        ings[i], stdout);
 
    /* calling qsort() to sort the array in ascending order */
    qsort(strings, NOSTRINGS, SIZE, string_compare);
    printf("\n");
 
    /* array of sorted strings */
    printf("After Sorting:\n");
    for (i = 0; i < NOSTRINGS; i++)
        printf(strings[i], stdout);
 
    return 0;
}
 
int string_compare(void const *str1, void const *str2)
{
    return strcmp((char *)str1, (char *)str2);
}

Output of the program is as follows

advertisement
advertisement
Before Sorting:
Linux Kernel Primer
Expert C Programming
Robert Love
Kernel Development
Pointers on C
 
After Sorting:
Expert C Programming
Kernel Development
Linux Kernel Primer
Pointers on C
Robert Love

‘bsearch()’ function is used in a C program to locate a given value in a sorted array using ‘binary search mechanism’. If the array isn’t sorted, result is undefined! If value is found, function returns pointer to the value otherwise returns NULL! A simple C program might further enforce this concept.

/* bsearch.c -- program calls bsearch() to search for a given value */
/* in the sorted array */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
 
#define NOSTRINGS 5
#define SIZE 26
 
int string_compare(void const *, void const *);
 
int main(void)
{
    int i;
    char strings[NOSTRINGS][SIZE];
    char search_str[SIZE];
    char *status;
 
    /* read strings from the user */
    printf("User, write in %d character strings...\n", NOSTRINGS);
    for (i= 0; i < NOSTRINGS; i++)
        fgets(strings[i], SIZE, stdin);
 
    printf("\n\n");
 
    /* display array of unsorted strings */
    printf("Before Sorting:\n");
    for (i = 0; i < NOSTRINGS; i++)
        fputs(strings[i], stdout);
 
    /* sort the array */
    qsort(strings, NOSTRINGS, SIZE, string_compare);
    printf("\n");
 
    /* array of sorted strings */
    printf("After Sorting:\n");
    for (i = 0; i < NOSTRINGS; i++)
        printf(strings[i], stdout);
 
    printf("\n\n");
 
    /* read the string to be searched for */
    printf("User, write in string you wish to search for...\n");
    fgets(search_str, SIZE, stdin);
    printf("\n");
 
    /* calling bsearch() to locate given string in the array */
    status = bsearch(search_str, strings, NOSTRINGS, SIZE, 
                       string_compare);
 
    /* verify if given value is found */
    assert(status != NULL);
    printf("desired string is found!\n");
 
    return 0;
}
 
int string_compare(void const *str1, void const *str2)
{
    return strcmp((char *)str1, (char *)str2);
}

Output of the program is as follows

User, write in 5 character strings...
kernel Development
Linux Kernel Primer
Robert Love
Pointers on C
Expert C Programming
 
 
Before Sorting:
kernel Development
Linux Kernel Primer
Robert Love
Pointers on C
Expert C Programming
 
After Sorting:
Expert C Programming
Linux Kernel Primer
Pointers on C
Robert Love
kernel Development
 
 
User, write in string you wish to search for...
Robert Love
 
desired string is found!

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

advertisement
If you wish to look at all C Tutorials, go to C Tutorials.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.