Using qsort
The standard library sort.
Using qsort is a free C Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
The Standard Library Sort
C's standard library provides qsort in <stdlib.h>. It sorts any array given a comparison function, so you rarely need to write your own sort.
The qsort Signature
The prototype is:
basepointer to the first elementnmembnumber of elementssizebytes per elementcompara comparison function pointer
void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
Writing a Comparator
The comparator receives two const void *. Cast them to the real type, dereference, and return negative, zero, or positive.
#include <stdio.h>
#include <stdlib.h>
int cmp_int(const void *a, const void *b) {
int x = *(const int *)a;
int y = *(const int *)b;
return (x > y) - (x < y); /* safe, no overflow */
}
int main(void) {
int a[] = {5, 2, 9, 1, 3};
qsort(a, 5, sizeof(int), cmp_int);
for (int i = 0; i < 5; i++) printf("%d ", a[i]);
printf("\n");
return 0;
}Avoid Subtraction in Comparators
Returning x - y can overflow for large integers, giving wrong results. Use the difference-of-booleans idiom (x > y) - (x < y) instead.
#include <stdio.h>
int main(void) {
int x = 2000000000, y = -2000000000;
printf("unsafe x-y = %d\n", x - y); /* overflow */
printf("safe = %d\n", (x > y) - (x < y));
return 0;
}Descending Order
To sort descending, just flip the comparison result.
#include <stdio.h>
#include <stdlib.h>
int cmp_desc(const void *a, const void *b) {
int x = *(const int *)a, y = *(const int *)b;
return (y > x) - (y < x);
}
int main(void) {
int a[] = {5, 2, 9, 1, 3};
qsort(a, 5, sizeof(int), cmp_desc);
for (int i = 0; i < 5; i++) printf("%d ", a[i]);
printf("\n");
return 0;
}Sorting Strings
To sort an array of char *, the comparator receives pointers to the pointers. Cast to const char * const * and call strcmp.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmp_str(const void *a, const void *b) {
const char *x = *(const char * const *)a;
const char *y = *(const char * const *)b;
return strcmp(x, y);
}
int main(void) {
const char *names[] = {"charlie", "alice", "bob"};
qsort(names, 3, sizeof(char *), cmp_str);
for (int i = 0; i < 3; i++) printf("%s ", names[i]);
printf("\n");
return 0;
}Sorting Structs
You can sort an array of structs by any field. Here we order people by age.
#include <stdio.h>
#include <stdlib.h>
typedef struct { char name[16]; int age; } Person;
int by_age(const void *a, const void *b) {
const Person *p = a, *q = b;
return (p->age > q->age) - (p->age < q->age);
}
int main(void) {
Person ppl[] = {{"Ann", 30}, {"Ben", 25}, {"Cid", 40}};
qsort(ppl, 3, sizeof(Person), by_age);
for (int i = 0; i < 3; i++) printf("%s %d\n", ppl[i].name, ppl[i].age);
return 0;
}Multi-Key Sorting
To break ties, compare a second field when the first is equal. This sorts by age, then name alphabetically.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct { char name[16]; int age; } Person;
int cmp(const void *a, const void *b) {
const Person *p = a, *q = b;
if (p->age != q->age)
return (p->age > q->age) - (p->age < q->age);
return strcmp(p->name, q->name);
}
int main(void) {
Person ppl[] = {{"Zoe", 30}, {"Amy", 30}, {"Bo", 25}};
qsort(ppl, 3, sizeof(Person), cmp);
for (int i = 0; i < 3; i++) printf("%d %s\n", ppl[i].age, ppl[i].name);
return 0;
}qsort Is Not Stable
The C standard does not require qsort to be stable. If you need stability, add a tie-breaker key (like the original index) to your comparator.
bsearch Companion
bsearch performs a binary search on a sorted array using the same comparator style. Pair it with qsort for fast lookups.
#include <stdio.h>
#include <stdlib.h>
int cmp_int(const void *a, const void *b) {
int x = *(const int *)a, y = *(const int *)b;
return (x > y) - (x < y);
}
int main(void) {
int a[] = {1, 3, 5, 7, 9};
int key = 7;
int *found = bsearch(&key, a, 5, sizeof(int), cmp_int);
printf("%s\n", found ? "found" : "missing");
return 0;
}Why Use qsort
The standard qsort is well-tested, often a tuned introsort hybrid, and works on any type. Reach for your own sort only when you need stability or special behavior the library cannot give.
Quick Check
Test your understanding of qsort.
Recap
You learned to use the standard library sort.
qsort(base, nmemb, size, compar)sorts any array- Comparators cast
const void *and return sign of comparison - Avoid subtraction; use
(x > y) - (x < y) qsortis not guaranteed stable;bsearchis its search companion
Frequently asked questions
Is the “Using qsort” lesson free?
Yes — the full text of “Using qsort” is free to read here on the web, and the C Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C Academy course, upgrade to CoddyKit PRO.
What will I learn in “Using qsort”?
The standard library sort. You practise C Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C Academy?
No prior experience is required. C Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Using qsort” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C Academy lesson?
Yes. Every C Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Bubble and Insertion Sort
- Quicksort
- Mergesort
- Using qsort