sorting names using c [c/c++]

Post Reply
Posts: 37
Joined: Sun Apr 17, 2022 9:20 pm

sorting names using c [c/c++]

Post by code10 »

To sort names in C, you can use the qsort function, which is part of the C Standard Library. This function takes a pointer to an array of elements, the number of elements in the array, the size of each element, and a comparison function as input and sorts the elements in ascending order.

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++)

  return 0;
In this example, we first include the necessary headers for the qsort, printf, puts, strlen, and NULL functions. Then, we define a comparison function for qsort, which takes two void pointers as input and returns an integer indicating the result of the comparison.

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.
Post Reply