Add Book to My BookshelfPurchase This Book Online

Chapter 16 - Miscellaneous Routines

UNIX Systems Programming for SVR4
David A. Curry
 Copyright © 1996 O'Reilly & Associates, Inc.

Sorting
Every version of UNIX provides the same function to sort a table of data “in place:”
    #include <stdlib.h>
    void qsort(void *base, size_t nel, size_t width,
            int (*compar)(const void *, const void *));
This function implements Quicksort, a reasonably efficient general-purpose sorting algorithm. The base parameter points to the first element of the table to be sorted; nel indicates the number of elements in the table, each of size width. The compar parameter is a pointer to a function that compares two elements of the table and returns less than, equal to, or greater than 0, depending on whether the first element is to be considered less than, equal to, or greater than the second element.
Example 16-6 shows a small program that sorts an array of numbers.
Example 16-6:  qsort
#include <stdlib.h>
#define NELEM   10
int compare(const void *, const void *);
int
main(void)
{
    int i;
    int array[NELEM];
    /*
     * Fill the array with numbers.
     */
    for (i = 0; i < NELEM; i++)
        array[NELEM - i - 1] = (i * i) & 0xf;
    /*
     * Print it.
     */
    printf("Before sorting:\n\t");
    for (i = 0; i < NELEM; i++)
        printf("%d ", array[i]);
    putchar('\n');
    /*
     * Sort it.
     */
    qsort(array, NELEM, sizeof(int), compare);
    /*
     * Print it again.
     */
    printf("After sorting:\n\t");
    for (i = 0; i < NELEM; i++)
        printf("%d ", array[i]);
    putchar('\n');
    exit(0);
}
/*
* compare - compare two integers.
*/
int
compare(const void *a, const void *b)
{
    int *aa, *bb;
    aa = (int *) a;
    bb = (int *) b;
    return(*aa - *bb);
}
    % qsort
    Before sorting:
            1 0 1 4 9 0 9 4 1 0
    After sorting:
            0 0 0 1 1 1 4 4 9 9

Previous SectionNext Section
Books24x7.com, Inc © 2000 –  Feedback