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