Understanding and Using the qsort Function in C
Introduction to qsort
qsort is a stnadard library function in C that implements a sorting algorithm, typical based on quicksort. It is designed to sort data of any type, making it a versatile tool for various applications.
Header File
To use qsort, include the following header:
#include <stdlib.h>
Function Parameters
qsort has the following prototype:
void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
- base: Pointer to the first element of the array to be sorted.
- nmemb: Number of elements in the array.
- size: Size in bytes of each element.
- compar: Pointer to a comparison function that defines the sort order.




Note: The void* type is a generic pointer that can hold addresses of any data type. It cannot be directly dereferenced or used in pointer arithmetic without casting.
Sorting Integer Data with qsort
Here's an example of using qsort to sort an array of integers:
#include <stdio.h>
#include <stdlib.h>
int compareIntegers(const void *a, const void *b) {
// Method 1: Explicit comparison
// int valA = *(int*)a;
// int valB = *(int*)b;
// if (valA > valB) return 1;
// else if (valA < valB) return -1;
// else return 0;
// Method 2: Direct subtraction (for ascending order)
return (*(int*)a - *(int*)b);
}
int main() {
int numbers[] = {2, 4, 6, 8, 0, 9, 7, 5, 3, 1};
int count = sizeof(numbers) / sizeof(numbers[0]);
qsort(numbers, count, sizeof(int), compareIntegers);
for (int i = 0; i < count; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
return 0;
}
Sorting Structure Data with qsort
qsort can also sort arrrays of structures. Below is an example with a student structure:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student {
char name[20];
int age;
};
// Compare by age
int compareByAge(const void *a, const void *b) {
return ((struct Student*)a)->age - ((struct Student*)b)->age;
}
// Compare by name
int compareByName(const void *a, const void *b) {
return strcmp(((struct Student*)a)->name, ((struct Student*)b)->name);
}
void sortByAge() {
struct Student students[] = {{"zhangsan", 20}, {"lisi", 30}, {"wangwu", 15}};
int count = sizeof(students) / sizeof(students[0]);
qsort(students, count, sizeof(struct Student), compareByAge);
for (int i = 0; i < count; i++) {
printf("%d ", students[i].age);
}
printf("\n");
}
void sortByName() {
struct Student students[] = {{"zhangsan", 20}, {"lisi", 30}, {"wangwu", 15}};
int count = sizeof(students) / sizeof(students[0]);
qsort(students, count, sizeof(struct Student), compareByName);
for (int i = 0; i < count; i++) {
printf("%s ", students[i].name);
}
printf("\n");
}
int main() {
sortByAge();
sortByName();
return 0;
}