IBM Metal C

Examples

Example 5. Quicksort

Quicksort is a partition exchange sort first described by C.A.R. Hoare in 1960. The version here is from GNU libc, which implements optimizations suggested by Robert Sedgewick. It has two phases,the partition phase and the sort phase. When the partition falls below a threshold value, then the routine switches to an insertion sort.

Quicksort works well for a variety of different kinds of input data, and is substantially faster than any other sorting method in typical applications. It is in-place, using only a small auxiliary stack, and requires time proportional to N log N on the average to sort N items.

Performance is stated to be: Worst case: Ο(n2), Best case: Ο(n log n) Average case: Ο(n log n)

The qsort() function sorts an array of n elements, each of width bytes in size, where the first element of the array is pointed to by pbase. The compare pointer points to a function, which you supply, that compares two array elements and returns an integer value specifying their relationship. The qsort() function calls the comparison function one or more times during the sort, passing pointers to two array elements on each call. The comparison function must compare the elements and return one of the following values:

The sorted array elements are stored in increasing order, as returned by the comparison function. To sort reverse order reverse the “greater than” and “less than” logic in the comparison function. If two elements are equal, their order in the sorted array is unspecified.

I modified this implementation to pass the comparator function the size of the elements to be compared.

Type Signature

extern void _quicksort (void *const pbase, size_t total_elems, size_t size, __compar_fn_t2 cmp);

 

Testing the routine for performance, an array of 10,000, 100-byte entries (1MB) took .05 seconds, on a zEnterprise 114 3.8GHz processor.

References

  1. Software—Practice and Experience, Vol. 23(11), 1249–1265 (November 1993) Engineering a Sort Function, Jon L. Bentley M. Douglas McIlroy

Copyright Notice for C Quicksort Code

Copyright (C) 1991,1992,1996,1997,1999,2004 Free Software Foundation, Inc. This file is part of the GNU C Library. Written by Douglas C. Schmidt (schmidt@ics.uci.edu).