Home > Electronics Tutorials > C Language Tutorial > stdlib.h - Searching and Sorting Functions - qsort

C Language Programming Library Reference Guide

stdlib.h - Searching and Sorting Functions - qsort

Declaration: void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*)); Sorts an array. The beginning of the array is pointed to by base. The array is nitems long with each element in the array size bytes long.

The elements are sorted in ascending order according to the compar function. This function takes two arguments. These arguments are two elements being compared. This function must return less than zero if the first argument is less than the second. It must return zero if the first argument is equal to the second. It must return greater than zero if the first argument is greater than the second.

If multiple elements are equal, the order they are sorted in the array is unspecified.

No value is returned.

Example:

#include<stdlib.h>
#include<stdio.h>
#include<string.h>

int main(void)
{
  char string_array[10][50]={"John",
                             "Jane",
                             "Mary",
                             "Rogery",
                             "Dave",
                             "Paul",
                             "Beavis",
                             "Astro",
                             "George",
                             "Elroy"};

  /* Sort the list */
  qsort(string_array,10,50,strcmp);

  /* Search for the item "Elroy" and print it */
  printf("%s",bsearch("Elroy",string_array,10,50,strcmp));

  return 0;
}
Note: To report broken links or to submit your projects, tutorials please email to Webmaster

Discover

     more......