1 #include <ccan/asort/asort.h>
4 #if HAVE_NESTED_FUNCTIONS
5 void _asort(void *base, size_t nmemb, size_t size,
6 int(*compar)(const void *, const void *, const void *ctx),
9 /* This gives bogus "warning: no previous prototype for ‘cmp’"
10 * with gcc 4 with -Wmissing-prototypes. Hence the auto crap. */
11 auto int cmp(const void *a, const void *b);
12 int cmp(const void *a, const void *b)
14 return compar(a, b, ctx);
16 qsort(base, nmemb, size, cmp);
19 /* Steal glibc's code. */
21 /* Copyright (C) 1991,1992,1996,1997,1999,2004 Free Software Foundation, Inc.
22 This file is part of the GNU C Library.
23 Written by Douglas C. Schmidt (schmidt@ics.uci.edu).
25 The GNU C Library is free software; you can redistribute it and/or
26 modify it under the terms of the GNU Lesser General Public
27 License as published by the Free Software Foundation; either
28 version 2.1 of the License, or (at your option) any later version.
30 The GNU C Library is distributed in the hope that it will be useful,
31 but WITHOUT ANY WARRANTY; without even the implied warranty of
32 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
33 Lesser General Public License for more details.
35 You should have received a copy of the GNU Lesser General Public
36 License along with the GNU C Library; if not, write to the Free
37 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
40 /* If you consider tuning this algorithm, you should consult first:
41 Engineering a sort function; Jon Bentley and M. Douglas McIlroy;
42 Software - Practice and Experience; Vol. 23 (11), 1249-1265, 1993. */
48 /* Byte-wise swap two items of size SIZE. */
49 #define SWAP(a, b, size) \
52 register size_t __size = (size); \
53 register char *__a = (a), *__b = (b); \
59 } while (--__size > 0); \
62 /* Discontinue quicksort algorithm when partition gets below this size.
63 This particular magic number was chosen to work best on a Sun 4/260. */
66 /* Stack node declarations used to store unfulfilled partition obligations. */
73 /* The next 4 #defines implement a very fast in-line stack abstraction. */
74 /* The stack needs log (total_elements) entries (we could even subtract
75 log(MAX_THRESH)). Since total_elements has type size_t, we get as
76 upper bound for log (total_elements):
77 bits per byte (CHAR_BIT) * sizeof(size_t). */
78 #define STACK_SIZE (CHAR_BIT * sizeof(size_t))
79 #define PUSH(low, high) ((void) ((top->lo = (low)), (top->hi = (high)), ++top))
80 #define POP(low, high) ((void) (--top, (low = top->lo), (high = top->hi)))
81 #define STACK_NOT_EMPTY (stack < top)
84 /* Order size using quicksort. This implementation incorporates
85 four optimizations discussed in Sedgewick:
87 1. Non-recursive, using an explicit stack of pointer that store the
88 next array partition to sort. To save time, this maximum amount
89 of space required to store an array of SIZE_MAX is allocated on the
90 stack. Assuming a 32-bit (64 bit) integer for size_t, this needs
91 only 32 * sizeof(stack_node) == 256 bytes (for 64 bit: 1024 bytes).
92 Pretty cheap, actually.
94 2. Chose the pivot element using a median-of-three decision tree.
95 This reduces the probability of selecting a bad pivot value and
96 eliminates certain extraneous comparisons.
98 3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving
99 insertion sort to order the MAX_THRESH items within each partition.
100 This is a big win, since insertion sort is faster for small, mostly
101 sorted array segments.
103 4. The larger of the two sub-partitions is always pushed onto the
104 stack first, with the algorithm then concentrating on the
105 smaller partition. This *guarantees* no more than log (total_elems)
106 stack size is needed (actually O(1) in this case)! */
109 _asort (void *const pbase, size_t total_elems, size_t size,
110 int(*cmp)(const void *, const void *, const void *arg),
113 register char *base_ptr = (char *) pbase;
115 const size_t max_thresh = MAX_THRESH * size;
117 if (total_elems == 0)
118 /* Avoid lossage with unsigned arithmetic below. */
121 if (total_elems > MAX_THRESH)
124 char *hi = &lo[size * (total_elems - 1)];
125 stack_node stack[STACK_SIZE];
126 stack_node *top = stack;
130 while (STACK_NOT_EMPTY)
135 /* Select median value from among LO, MID, and HI. Rearrange
136 LO and HI so the three values are sorted. This lowers the
137 probability of picking a pathological pivot value and
138 skips a comparison for both the LEFT_PTR and RIGHT_PTR in
141 char *mid = lo + size * ((hi - lo) / size >> 1);
143 if ((*cmp) ((void *) mid, (void *) lo, arg) < 0)
144 SWAP (mid, lo, size);
145 if ((*cmp) ((void *) hi, (void *) mid, arg) < 0)
146 SWAP (mid, hi, size);
149 if ((*cmp) ((void *) mid, (void *) lo, arg) < 0)
150 SWAP (mid, lo, size);
153 left_ptr = lo + size;
154 right_ptr = hi - size;
156 /* Here's the famous ``collapse the walls'' section of quicksort.
157 Gotta like those tight inner loops! They are the main reason
158 that this algorithm runs much faster than others. */
161 while ((*cmp) ((void *) left_ptr, (void *) mid, arg) < 0)
164 while ((*cmp) ((void *) mid, (void *) right_ptr, arg) < 0)
167 if (left_ptr < right_ptr)
169 SWAP (left_ptr, right_ptr, size);
172 else if (mid == right_ptr)
177 else if (left_ptr == right_ptr)
184 while (left_ptr <= right_ptr);
186 /* Set up pointers for next iteration. First determine whether
187 left and right partitions are below the threshold size. If so,
188 ignore one or both. Otherwise, push the larger partition's
189 bounds on the stack and continue sorting the smaller one. */
191 if ((size_t) (right_ptr - lo) <= max_thresh)
193 if ((size_t) (hi - left_ptr) <= max_thresh)
194 /* Ignore both small partitions. */
197 /* Ignore small left partition. */
200 else if ((size_t) (hi - left_ptr) <= max_thresh)
201 /* Ignore small right partition. */
203 else if ((right_ptr - lo) > (hi - left_ptr))
205 /* Push larger left partition indices. */
206 PUSH (lo, right_ptr);
211 /* Push larger right partition indices. */
218 /* Once the BASE_PTR array is partially sorted by quicksort the rest
219 is completely sorted using insertion sort, since this is efficient
220 for partitions below MAX_THRESH size. BASE_PTR points to the beginning
221 of the array to sort, and END_PTR points at the very last element in
222 the array (*not* one beyond it!). */
224 #define min(x, y) ((x) < (y) ? (x) : (y))
227 char *const end_ptr = &base_ptr[size * (total_elems - 1)];
228 char *tmp_ptr = base_ptr;
229 char *thresh = min(end_ptr, base_ptr + max_thresh);
230 register char *run_ptr;
232 /* Find smallest element in first threshold and place it at the
233 array's beginning. This is the smallest array element,
234 and the operation speeds up insertion sort's inner loop. */
236 for (run_ptr = tmp_ptr + size; run_ptr <= thresh; run_ptr += size)
237 if ((*cmp) ((void *) run_ptr, (void *) tmp_ptr, arg) < 0)
240 if (tmp_ptr != base_ptr)
241 SWAP (tmp_ptr, base_ptr, size);
243 /* Insertion sort, running from left-hand-side up to right-hand-side. */
245 run_ptr = base_ptr + size;
246 while ((run_ptr += size) <= end_ptr)
248 tmp_ptr = run_ptr - size;
249 while ((*cmp) ((void *) run_ptr, (void *) tmp_ptr, arg) < 0)
253 if (tmp_ptr != run_ptr)
257 trav = run_ptr + size;
258 while (--trav >= run_ptr)
263 for (hi = lo = trav; (lo -= size) >= tmp_ptr; hi = lo)
271 #endif /* !HAVE_NESTED_FUNCTIONS */