qsort

De RAD Studio
Aller à : navigation, rechercher

Remonter à Stdlib.h - Index


Header File

stdlib.h

Category

Memory and String Manipulation Routines

Prototype

void qsort(void *base, size_t nelem, size_t width, int (_USERENTRY *fcmp)(const void *, const void *));

Description

Sorts using the quicksort algorithm.

qsort is an implementation of the “median of three” variant of the quicksort algorithm. qsort sorts the entries in a table by repeatedly calling the user-defined comparison function pointed to by fcmp.

  • base points to the base (0th element) of the table to be sorted.
  • nelem is the number of entries in the table.
  • width is the size of each entry in the table, in bytes.

fcmp, the comparison function, must be used with the _USERENTRY calling convention.

  • fcmp accepts two arguments, elem1 and elem2, each a pointer to an entry in the table. The comparison function compares each of the pointed-to items (*elem1 and *elem2), and returns an integer based on the result of the comparison.
  • *elem1 < *elem2 fcmp returns an integer < 0
  • *elem1 == *elem2 fcmp returns 0
  • *elem1 > *elem2 fcmp returns an integer > 0

In the comparison, the less-than symbol (<) means the left element should appear before the right element in the final, sorted sequence. Similarly, the greater-than (>) symbol means the left element should appear after the right element in the final, sorted sequence.

Return Value

None.

Example



 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 int sort_function( const void *a, const void *b);
 char list[5][4] = { "cat", "car", "cab", "cap", "can" };
 int main(void)
 {
    int  x;
    qsort((void *)list, 5, sizeof(list[0]), sort_function);
    for (x = 0; x < 5; x++)
       printf("%s\n", list[x]);
    return 0;
 }
 int sort_function( const void *a, const void *b)
 {
    return( strcmp((char *)a,(char *)b) );
 }



Portability



POSIX Win32 ANSI C ANSI C++

+

+

+

+