Here is an example of how you might use qsort to sort a list of names in C:
Code: Select all
#include <stdio.h> // for printf and puts
#include <stdlib.h> // for qsort and NULL
#include <string.h> // for strlen
// comparison function for qsort
int compare(const void *a, const void *b)
{
// cast the void pointers to char pointers
char *ca = *(char **) a;
char *cb = *(char **) b;
// compare the strings and return the result
return strcmp(ca, cb);
}
int main()
{
char *names[] = { "John", "Jane", "Bob", "Alice" };
// sort the names using qsort
qsort(names, sizeof(names) / sizeof(names[0]), sizeof(char *), compare);
// print the sorted names
for (int i = 0; i < sizeof(names) / sizeof(names[0]); i++)
{
puts(names[i]);
}
return 0;
}
Next, we create an array of character pointers called names and initialize it with a list of names. Then, we use qsort to sort the elements in the array in ascending order. The sizeof operator is used to determine the number of elements in the array, and the sizeof operator is used to determine the size of each element.
Finally, we print the sorted names to the console using the puts function in a loop. This will print the names in alphabetical order, with "Alice" being the first name and "John" being the last.
using qsort is a simple and efficient way to sort a list of names in C.