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