To sort an array in C, you can use the qsort() function from the stdlib.h library.
In this example,
numbers
with values 5, 2, 8, 1, 6.compare
that compares two integers.qsort()
function with our compare function to sort the array in ascending order.numbers
to the console.#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
int main() {
int numbers[] = {5, 2, 8, 1, 6};
int n = sizeof(numbers) / sizeof(numbers[0]);
qsort(numbers, n, sizeof(int), compare);
printf("Sorted array in ascending order: ");
for (int i = 0; i < n; i++) {
printf("%d ", numbers[i]);
}
return 0;
}
Sorted array in ascending order: 1 2 5 6 8
In this example,
numbers
with values 5, 2, 8, 1, 6.compare
that compares two integers in reverse order.qsort()
function with our reverse compare function to sort the array in descending order.numbers
to the console.#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
return (*(int*)b - *(int*)a);
}
int main() {
int numbers[] = {5, 2, 8, 1, 6};
int n = sizeof(numbers) / sizeof(numbers[0]);
qsort(numbers, n, sizeof(int), compare);
printf("Sorted array in descending order: ");
for (int i = 0; i < n; i++) {
printf("%d ", numbers[i]);
}
return 0;
}
Sorted array in descending order: 8 6 5 2 1
In this tutorial, we learned How to Sort an Array in C language with well detailed examples.