The qsort() function in C is a standard library function used to sort the elements of an array. It is declared in the <stdlib.h> header file and uses a comparison function to determine the order of elements.
- It can sort arrays of integers, strings, structures, and other data types.
- The comparison function determines the relative order of two elements.
- The C standard does not specify the sorting algorithm used internally by qsort().
Let's take a look at an example that sorts an array of integers using the qsort()
#include <stdio.h>
#include <stdlib.h>
int comp(const void *a, const void *b) {
int x = *(const int *)a;
int y = *(const int *)b;
if (x < y)
return -1;
if (x > y)
return 1;
return 0;
}
int main() {
int arr[] = {5, 2, 3, 1, 4};
int n = sizeof(arr) / sizeof(arr[0]);
// Sort the array
qsort(arr, n, sizeof(arr[0]), comp);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output
1 2 3 4 5
Syntax
qsort(array, count, size, compare);
Parameters
- array: Pointer to the first element of the array to be sorted.
- count: Number of elements in the array.
- size: Size of each element in bytes.
- compare: Pointer to the comparison function that determines the order of elements.
Return Value: The
qsort()function does not return a value.
Rules for Defining Comparison Function
The comparison function determines the relative ordering of two elements passed to qsort().
- It should accept two
const void *arguments. - It should return a value less than 0 if the first element should appear before the second element.
- It should return 0 if the two elements are considered equal.
- It should return a value greater than 0 if the first element should appear after the second element.
- The arguments should be converted to the appropriate pointer type before accessing their values.
- Integer values should not be directly subtracted in the comparator because the subtraction can cause integer overflow for extreme values.
- The comparator should define a consistent ordering for the elements.
Note: The comparison function can interpret the
const void *arguments according to the type of elements being sorted, allowingqsort()to work with different data types.
Examples of qsort()
The qsort() function can sort different types of arrays by using an appropriate comparison function.
Sort an Array of Integers in Descending Order
#include <stdio.h>
#include <stdlib.h>
int comp(const void *a, const void *b) {
int x = *(const int *)a;
int y = *(const int *)b;
if (x < y)
return 1;
if (x > y)
return -1;
return 0;
}
int main() {
int arr[] = {5, 2, 3, 1, 4};
int n = sizeof(arr) / sizeof(arr[0]);
qsort(arr, n, sizeof(arr[0]), comp);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output
5 4 3 2 1
Sort an Array of Strings Lexicographically
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compare(const void *a, const void *b) {
const char *str1 = *(const char * const *)a;
const char *str2 = *(const char * const *)b;
return strcmp(str1, str2);
}
int main() {
const char *arr[] = {"Welcome", "to", "Geeks", "for", "Geeks"};
int n = sizeof(arr) / sizeof(arr[0]);
qsort(arr, n, sizeof(arr[0]), compare);
for (int i = 0; i < n; i++)
printf("%s ", arr[i]);
return 0;
}
Output
Geeks Geeks Welcome for to
Sort an Array of Structures
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int data;
} A;
int comp(const void *a, const void *b) {
const A *x = a;
const A *y = b;
if (x->data < y->data)
return -1;
if (x->data > y->data)
return 1;
return 0;
}
int main() {
A arr[] = {{5}, {2}, {3}, {1}, {4}};
int n = sizeof(arr) / sizeof(arr[0]);
qsort(arr, n, sizeof(arr[0]), comp);
for (int i = 0; i < n; i++)
printf("%d ", arr[i].data);
return 0;
}
Output
1 2 3 4 5
Common Mistakes When Using qsort()
The following mistakes can cause incorrect results, undefined behavior, or runtime issues:
- Using an incorrect comparison function signature.
- Accessing the arguments without converting const void * to the correct data type.
- Subtracting integers directly in the comparator, which can cause integer overflow.
- Passing an incorrect number of elements or element size to qsort().
- Using an incorrect comparator that does not consistently define the ordering of elements.
- Using strcmp() incorrectly when sorting an array of string pointers.
- Accessing invalid or uninitialized memory inside the comparison function.
Advantages of qsort()
- It is part of the C standard library and does not require a separate sorting library.
- It can sort arrays containing different data types.
- It uses a comparison function, allowing the programmer to define custom sorting orders.
- It can be used to sort arrays of structures and other user-defined data types.
Limitations of qsort()
- The comparison function must be implemented correctly for the data type being sorted.
- Its interface uses void *, which requires type conversion inside the comparator.
- The C standard does not guarantee a particular sorting algorithm or complexity for qsort().
- It does not provide a built-in way to pass additional user-defined context to the comparison function.