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