Skip to content

Commit

Permalink
manual: Correct guarantee about pointers compared by qsort()
Browse files Browse the repository at this point in the history
C99, C11, POSIX, and the glibc implementation do guarantee that the
pointers passed to the qsort comparison function lie within the array.

Signed-off-by: Anders Kaseorg <andersk@mit.edu>
  • Loading branch information
Anders Kaseorg authored and Ondřej Bílka committed Dec 21, 2014
1 parent d12455f commit 98fe149
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
5 changes: 5 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
2014-12-21 Anders Kaseorg <andersk@mit.edu>

* manual/search.texi: (Array Sort Function): Clarify stable sorting
guarantees.

2014-12-20 Chris Metcalf <cmetcalf@ezchip.com>

* sysdeps/unix/sysv/linux/tile/localplt.data: New file.
Expand Down
14 changes: 8 additions & 6 deletions manual/search.texi
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,8 @@ To sort an array using an arbitrary comparison function, use the
@comment ISO
@deftypefun void qsort (void *@var{array}, size_t @var{count}, size_t @var{size}, comparison_fn_t @var{compare})
@safety{@prelim{}@mtsafe{}@assafe{}@acunsafe{@acucorrupt{}}}
The @var{qsort} function sorts the array @var{array}. The array contains
@var{count} elements, each of which is of size @var{size}.
The @code{qsort} function sorts the array @var{array}. The array
contains @var{count} elements, each of which is of size @var{size}.

The @var{compare} function is used to perform the comparison on the
array elements. This function is called with two pointer arguments and
Expand All @@ -180,10 +180,12 @@ This can make a difference when the comparison considers only part of
the elements. Two elements with the same sort key may differ in other
respects.

The addresses passed to the comparison function need not correspond with
the original location of the objects, and need not even lie within the
original array. The only way to perform a stable sort with @var{qsort}
is to first augment the objects with a monotonic counter of some kind.
Although the object addresses passed to the comparison function lie
within the array, they need not correspond with the original locations
of those objects because the sorting algorithm may swap around objects
in the array before making some comparisons. The only way to perform
a stable sort with @code{qsort} is to first augment the objects with a
monotonic counter of some kind.

Here is a simple example of sorting an array of doubles in numerical
order, using the comparison function defined above (@pxref{Comparison
Expand Down

0 comments on commit 98fe149

Please sign in to comment.