To sort an array in ascending order in C, you can use the `qsort` function from the `stdlib.h` library for both arrays of integers and arrays of strings.
In this example,
numbers
.compareInts
, to compare two integers.qsort
function to sort the array of integers in-place based on the comparison function.#include <stdio.h>
#include <stdlib.h>
int compareInts(const void* a, const void* b) {
return (*(int*)a - *(int*)b);
}
int main() {
int numbers[] = {5, 2, 8, 1, 9};
int size = sizeof(numbers) / sizeof(numbers[0]);
qsort(numbers, size, sizeof(int), compareInts);
for (int i = 0; i < size; i++) {
printf("%d ", numbers[i]);
}
return 0;
}
1 2 5 8 9
In this example,
words
.compareStrings
, to compare two strings.qsort
function to sort the array of strings in-place based on the comparison function.#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compareStrings(const void* a, const void* b) {
return strcmp(*(const char**)a, *(const char**)b);
}
int main() {
char* words[] = {"apple", "banana", "cherry", "date"};
int size = sizeof(words) / sizeof(words[0]);
qsort(words, size, sizeof(char*), compareStrings);
for (int i = 0; i < size; i++) {
printf("%s ", words[i]);
}
return 0;
}
apple banana cherry date
In this tutorial, we learned How to Sort an Array in Ascending Order in C language with well detailed examples.