Remove K&R compatibility.
[glibc.git] / stdlib / qsort.c
blobf14acb6abb4948dcb8ae36ecfec12a43bd568f33
1 /* Copyright (C) 1991, 1992, 1996, 1997, 1999 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3 Written by Douglas C. Schmidt (schmidt@ics.uci.edu).
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
15 You should have received a copy of the GNU Library General Public
16 License along with the GNU C Library; see the file COPYING.LIB. If not,
17 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA. */
20 /* If you consider tuning this algorithm, you should consult first:
21 Engineering a sort function; Jon Bentley and M. Douglas McIlroy;
22 Software - Practice and Experience; Vol. 23 (11), 1249-1265, 1993. */
24 #include <alloca.h>
25 #include <limits.h>
26 #include <stdlib.h>
27 #include <string.h>
29 /* Byte-wise swap two items of size SIZE. */
30 #define SWAP(a, b, size) \
31 do \
32 { \
33 register size_t __size = (size); \
34 register char *__a = (a), *__b = (b); \
35 do \
36 { \
37 char __tmp = *__a; \
38 *__a++ = *__b; \
39 *__b++ = __tmp; \
40 } while (--__size > 0); \
41 } while (0)
43 /* Discontinue quicksort algorithm when partition gets below this size.
44 This particular magic number was chosen to work best on a Sun 4/260. */
45 #define MAX_THRESH 4
47 /* Stack node declarations used to store unfulfilled partition obligations. */
48 typedef struct
50 char *lo;
51 char *hi;
52 } stack_node;
54 /* The next 4 #defines implement a very fast in-line stack abstraction. */
55 /* The stack needs log (total_elements) entries (we could even subtract
56 log(MAX_THRESH)). Since total_elements has type size_t, we get as
57 upper bound for log (total_elements):
58 bits per byte (CHAR_BIT) * sizeof(size_t). */
59 #define STACK_SIZE (CHAR_BIT * sizeof(size_t))
60 #define PUSH(low, high) ((void) ((top->lo = (low)), (top->hi = (high)), ++top))
61 #define POP(low, high) ((void) (--top, (low = top->lo), (high = top->hi)))
62 #define STACK_NOT_EMPTY (stack < top)
65 /* Order size using quicksort. This implementation incorporates
66 four optimizations discussed in Sedgewick:
68 1. Non-recursive, using an explicit stack of pointer that store the
69 next array partition to sort. To save time, this maximum amount
70 of space required to store an array of SIZE_MAX is allocated on the
71 stack. Assuming a 32-bit (64 bit) integer for size_t, this needs
72 only 32 * sizeof(stack_node) == 256 bytes (for 64 bit: 1024 bytes).
73 Pretty cheap, actually.
75 2. Chose the pivot element using a median-of-three decision tree.
76 This reduces the probability of selecting a bad pivot value and
77 eliminates certain extraneous comparisons.
79 3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving
80 insertion sort to order the MAX_THRESH items within each partition.
81 This is a big win, since insertion sort is faster for small, mostly
82 sorted array segments.
84 4. The larger of the two sub-partitions is always pushed onto the
85 stack first, with the algorithm then concentrating on the
86 smaller partition. This *guarantees* no more than log (total_elems)
87 stack size is needed (actually O(1) in this case)! */
89 void
90 _quicksort (void *const pbase, size_t total_elems, size_t size,
91 __compar_fn_t cmp)
93 register char *base_ptr = (char *) pbase;
95 /* Allocating SIZE bytes for a pivot buffer facilitates a better
96 algorithm below since we can do comparisons directly on the pivot. */
97 char *pivot_buffer = (char *) __alloca (size);
98 const size_t max_thresh = MAX_THRESH * size;
100 if (total_elems == 0)
101 /* Avoid lossage with unsigned arithmetic below. */
102 return;
104 if (total_elems > MAX_THRESH)
106 char *lo = base_ptr;
107 char *hi = &lo[size * (total_elems - 1)];
108 stack_node stack[STACK_SIZE];
109 stack_node *top = stack + 1;
111 while (STACK_NOT_EMPTY)
113 char *left_ptr;
114 char *right_ptr;
116 char *pivot = pivot_buffer;
118 /* Select median value from among LO, MID, and HI. Rearrange
119 LO and HI so the three values are sorted. This lowers the
120 probability of picking a pathological pivot value and
121 skips a comparison for both the LEFT_PTR and RIGHT_PTR in
122 the while loops. */
124 char *mid = lo + size * ((hi - lo) / size >> 1);
126 if ((*cmp) ((void *) mid, (void *) lo) < 0)
127 SWAP (mid, lo, size);
128 if ((*cmp) ((void *) hi, (void *) mid) < 0)
129 SWAP (mid, hi, size);
130 else
131 goto jump_over;
132 if ((*cmp) ((void *) mid, (void *) lo) < 0)
133 SWAP (mid, lo, size);
134 jump_over:;
135 memcpy (pivot, mid, size);
136 pivot = pivot_buffer;
138 left_ptr = lo + size;
139 right_ptr = hi - size;
141 /* Here's the famous ``collapse the walls'' section of quicksort.
142 Gotta like those tight inner loops! They are the main reason
143 that this algorithm runs much faster than others. */
146 while ((*cmp) ((void *) left_ptr, (void *) pivot) < 0)
147 left_ptr += size;
149 while ((*cmp) ((void *) pivot, (void *) right_ptr) < 0)
150 right_ptr -= size;
152 if (left_ptr < right_ptr)
154 SWAP (left_ptr, right_ptr, size);
155 left_ptr += size;
156 right_ptr -= size;
158 else if (left_ptr == right_ptr)
160 left_ptr += size;
161 right_ptr -= size;
162 break;
165 while (left_ptr <= right_ptr);
167 /* Set up pointers for next iteration. First determine whether
168 left and right partitions are below the threshold size. If so,
169 ignore one or both. Otherwise, push the larger partition's
170 bounds on the stack and continue sorting the smaller one. */
172 if ((size_t) (right_ptr - lo) <= max_thresh)
174 if ((size_t) (hi - left_ptr) <= max_thresh)
175 /* Ignore both small partitions. */
176 POP (lo, hi);
177 else
178 /* Ignore small left partition. */
179 lo = left_ptr;
181 else if ((size_t) (hi - left_ptr) <= max_thresh)
182 /* Ignore small right partition. */
183 hi = right_ptr;
184 else if ((right_ptr - lo) > (hi - left_ptr))
186 /* Push larger left partition indices. */
187 PUSH (lo, right_ptr);
188 lo = left_ptr;
190 else
192 /* Push larger right partition indices. */
193 PUSH (left_ptr, hi);
194 hi = right_ptr;
199 /* Once the BASE_PTR array is partially sorted by quicksort the rest
200 is completely sorted using insertion sort, since this is efficient
201 for partitions below MAX_THRESH size. BASE_PTR points to the beginning
202 of the array to sort, and END_PTR points at the very last element in
203 the array (*not* one beyond it!). */
205 #define min(x, y) ((x) < (y) ? (x) : (y))
208 char *const end_ptr = &base_ptr[size * (total_elems - 1)];
209 char *tmp_ptr = base_ptr;
210 char *thresh = min(end_ptr, base_ptr + max_thresh);
211 register char *run_ptr;
213 /* Find smallest element in first threshold and place it at the
214 array's beginning. This is the smallest array element,
215 and the operation speeds up insertion sort's inner loop. */
217 for (run_ptr = tmp_ptr + size; run_ptr <= thresh; run_ptr += size)
218 if ((*cmp) ((void *) run_ptr, (void *) tmp_ptr) < 0)
219 tmp_ptr = run_ptr;
221 if (tmp_ptr != base_ptr)
222 SWAP (tmp_ptr, base_ptr, size);
224 /* Insertion sort, running from left-hand-side up to right-hand-side. */
226 run_ptr = base_ptr + size;
227 while ((run_ptr += size) <= end_ptr)
229 tmp_ptr = run_ptr - size;
230 while ((*cmp) ((void *) run_ptr, (void *) tmp_ptr) < 0)
231 tmp_ptr -= size;
233 tmp_ptr += size;
234 if (tmp_ptr != run_ptr)
236 char *trav;
238 trav = run_ptr + size;
239 while (--trav >= run_ptr)
241 char c = *trav;
242 char *hi, *lo;
244 for (hi = lo = trav; (lo -= size) >= tmp_ptr; hi = lo)
245 *hi = *lo;
246 *hi = c;