You do not need to write your own sorting algorithm in C every time. The standard library function qsort sorts an array of any type, numbers, strings or structures, as long as you give it a comparison function that says which of two elements should come first. Its partner bsearch finds an element in a sorted array in logarithmic time. This lesson shows how both work and how to write correct comparators.
In this lesson you will learn
- The four arguments of
qsort - Writing comparison functions with
const void *parameters - Ascending, descending and multi-key sorting
- Sorting arrays of structs and of strings
- Searching a sorted array with
bsearch
This lesson uses function pointers and void pointers.
Sorting Numbers and Searching
#include <stdio.h>
#include <stdlib.h>
static int cmp_int_asc(const void *a, const void *b) {
int x = *(const int *)a, y = *(const int *)b;
return (x > y) - (x < y); /* -1, 0 or 1, no overflow */
}
static int cmp_int_desc(const void *a, const void *b) {
return cmp_int_asc(b, a);
}
static void print(const int *a, size_t n) {
for (size_t i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n");
}
int main(void) {
int marks[] = {72, 95, 60, 88, 95, 41};
size_t n = sizeof marks / sizeof marks[0];
qsort(marks, n, sizeof marks[0], cmp_int_asc);
print(marks, n);
qsort(marks, n, sizeof marks[0], cmp_int_desc);
print(marks, n);
qsort(marks, n, sizeof marks[0], cmp_int_asc);
int key = 88;
int *found = bsearch(&key, marks, n, sizeof marks[0], cmp_int_asc);
if (found) printf("found %d at index %td\n", key, found - marks);
return 0;
}
Output
41 60 72 88 95 95
95 95 88 72 60 41
found 88 at index 3
qsort(base, count, size, compare)takes the array, the number of elements, the size of one element and a pointer to the comparison function.sizeof marks / sizeof marks[0]computes the element count. It only works on a real array, not on a pointer passed into a function.- The comparator receives two
const void *pointers to elements. It casts them to the real type and returns a negative number if the first should come first, zero if they are equal, and a positive number otherwise. (x > y) - (x < y)produces -1, 0 or 1 safely. The temptingreturn x - y;can overflow for large or negative values and give the wrong order.- For descending order, compare the arguments the other way round.
bsearchtakes the same arguments plus a pointer to the key, and returns a pointer to a matching element orNULL. The array must be sorted with the same comparator. Subtracting pointers gives the index.
Sorting Structures and Strings
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char name[16];
char dept[4];
double cgpa;
} Student;
static int by_cgpa_desc(const void *a, const void *b) {
const Student *x = a, *y = b;
return (y->cgpa > x->cgpa) - (y->cgpa < x->cgpa);
}
static int by_dept_then_name(const void *a, const void *b) {
const Student *x = a, *y = b;
int d = strcmp(x->dept, y->dept);
return d != 0 ? d : strcmp(x->name, y->name);
}
static int by_string(const void *a, const void *b) {
const char *const *x = a, *const *y = b; /* elements are char* */
return strcmp(*x, *y);
}
int main(void) {
Student s[] = {
{"Nusrat", "CSE", 3.82}, {"Arif", "EEE", 3.41},
{"Tania", "CSE", 3.95}, {"Rafi", "EEE", 2.98}, {"Imran", "BBA", 3.10},
};
size_t n = sizeof s / sizeof s[0];
qsort(s, n, sizeof s[0], by_cgpa_desc);
for (size_t i = 0; i < n; i++) printf("%-7s %.2f\n", s[i].name, s[i].cgpa);
qsort(s, n, sizeof s[0], by_dept_then_name);
for (size_t i = 0; i < n; i++) printf("%s:%s ", s[i].dept, s[i].name);
printf("\n");
const char *cities[] = {"Sylhet", "Dhaka", "Khulna", "Barishal"};
qsort(cities, 4, sizeof cities[0], by_string);
for (int i = 0; i < 4; i++) printf("%s ", cities[i]);
printf("\n");
return 0;
}
Output
Tania 3.95
Nusrat 3.82
Arif 3.41
Imran 3.10
Rafi 2.98
BBA:Imran CSE:Nusrat CSE:Tania EEE:Arif EEE:Rafi
Barishal Dhaka Khulna Sylhet
- For an array of structs, each element pointer is a
const Student *. Assigningconst void *to it needs no cast in C. by_dept_then_namesorts by a second key when the first is equal: department first, then name.- In an array of strings (
const char *cities[]) each element is itself a pointer, so the comparator receives a pointer to a pointer. Dereference once to get the string, then callstrcmp. Passing the parameters straight tostrcmpis a classic bug. qsortis not guaranteed to be stable: elements that compare equal may change their relative order. Add a tie-breaking key if order matters.
Comparator Patterns
| Array of | Cast to | Compare with |
|---|---|---|
int | const int * | (x > y) - (x < y) |
double | const double * | (x > y) - (x < y) |
char * strings | const char *const * | strcmp(*x, *y) |
char name[20][16] (2D char array) | const char * | strcmp(x, y) |
| Structs | const Type * | Field by field |
Common Mistakes
- Returning
a - bfor ints or doubles; overflow and truncation give wrong results. - Wrong element size: always use
sizeof arr[0]rather than a hard-coded number. - Treating string-array elements as strings in the comparator instead of pointers to strings.
- Calling bsearch on unsorted data or with a different comparator from the sort.
Practice Exercises
Exercise 1. Sort an array of doubles in descending order.
Show answer
int cmp_desc(const void *a, const void *b) {
double x = *(const double *)a, y = *(const double *)b;
return (y > x) - (y < x);
}
/* qsort(arr, n, sizeof arr[0], cmp_desc); */
Exercise 2. Sort strings by length, shortest first, and alphabetically when lengths are equal.
Show answer
int by_len(const void *a, const void *b) {
const char *x = *(const char *const *)a, *y = *(const char *const *)b;
size_t lx = strlen(x), ly = strlen(y);
if (lx != ly) return (lx > ly) - (lx < ly);
return strcmp(x, y);
}
Frequently Asked Questions
Does qsort always use quicksort?
No. The C standard only says what qsort does, not how. glibc, for example, has used merge sort or introsort in different versions. Expect O(n log n) time but do not rely on a specific algorithm.
When should I write my own sort instead?
When learning algorithms, when you need a stable sort, or in very performance-critical code where a type-specific sort avoids function-call overhead. The DSA tutorials implement the classic algorithms.
Summary
qsort(base, n, size, cmp)sorts any array using your comparator.- Comparators return negative, zero or positive; avoid subtraction.
- For string arrays, the comparator receives pointers to pointers.
bsearchfinds items in a sorted array in O(log n).
