| qsort | Function (tigcc.a)

stdlib.h

void qsort (void *BasePtr, unsigned short NoOfElements, unsigned short Width, compare_t cmp_func);

Sorts an area of items.

qsort sorts the entries in a table by repeatedly calling the user-defined comparison function pointed to by cmp_func. BasePtr points to the base (0-th element) of the table to be sorted. NoOfElement is the number of entries in the table. Width is the size of each entry in the table, in bytes. cmp_func, the comparison function, 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 a short integer based on the result of the comparison:

- If *elem1 < *elem2, cmp_func should return an integer < 0.
- If *elem1 == *elem2, cmp_func should return 0.
- If *elem1 > *elem2, cmp_func should return 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.
The ANSI standard proposes that the comparison function has to return a long integer. However, strcmp, which is frequently used as a comparison function, returns a short integer.
Here is a complete example of usage (called "Sort Integers"):

    // Sort a list of integer values

    #define USE_TI89              // Compile for TI-89
    #define USE_TI92PLUS          // Compile for TI-92 Plus
    #define USE_V200              // Compile for V200

    #define MIN_AMS 100           // Compile for AMS 1.00 or higher
    #define SAVE_SCREEN           // Save/Restore LCD Contents

    #include <tigcclib.h>         // Include All Header Files

    // Comparison Function
    CALLBACK short int_comp(const void *a, const void *b)
    {
      return fcmp (*(const short*)a, *(const short*)b);
    }

    // Main Function
    void _main(void)
    {
      short list[10] = {2, 9, 3, 6, 4, 2, 3, 3, 1, 5};
      int i;
      clrscr ();
      qsort (list, 10, sizeof (short), int_comp);
      for (i = 0; i < 10; i++)
        printf ("%d ", list[i]);
      ngetchx ();
    }

Note that the function strcmp is ideal for string comparisons. However, its parameters are not void pointers. This may be solved using a typecast like

    qsort (StringArray, NoOfStrings, LenOfEachString, (compare_t) strcmp);