Fix the fix to really close 181
[sxemacs] / lib-src / qsort.c
1 /* Plug-compatible replacement for UNIX qsort.
2    Copyright (C) 1989 Free Software Foundation, Inc.
3    Written by Douglas C. Schmidt (schmidt@ics.uci.edu)
4
5 This file is part of GNU CC.
6
7 GNU QSORT is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
11
12 GNU QSORT is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program.  If not, see <http://www.gnu.org/licenses/>. */
19
20 /* Synched up with: FSF 19.28. */
21
22 #ifdef sparc
23 #include <alloca.h>
24 #endif
25
26 /* Invoke the comparison function, returns either 0, < 0, or > 0. */
27 #define CMP(A,B) ((*cmp)((A),(B)))
28
29 /* Byte-wise swap two items of size SIZE. */
30 #define SWAP(A,B,SIZE) do {int sz = (SIZE); char *a = (A); char *b = (B); \
31     do { char _temp = *a;*a++ = *b;*b++ = _temp;} while (--sz);} while (0)
32
33 /* Copy SIZE bytes from item B to item A. */
34 #define COPY(A,B,SIZE) {int sz = (SIZE); do { *(A)++ = *(B)++; } while (--sz); }
35
36 /* This should be replaced by a standard ANSI macro. */
37 #define BYTES_PER_WORD 8
38
39 /* The next 4 #defines implement a very fast in-line stack abstraction. */
40 #define STACK_SIZE (BYTES_PER_WORD * sizeof (long))
41 #define PUSH(LOW,HIGH) do {top->lo = LOW;top++->hi = HIGH;} while (0)
42 #define POP(LOW,HIGH)  do {LOW = (--top)->lo;HIGH = top->hi;} while (0)
43 #define STACK_NOT_EMPTY (stack < top)
44
45 /* Discontinue quicksort algorithm when partition gets below this size.
46    This particular magic number was chosen to work best on a Sun 4/260. */
47 #define MAX_THRESH 4
48
49 /* Stack node declarations used to store unfulfilled partition obligations. */
50 typedef struct {
51         char *lo;
52         char *hi;
53 } stack_node;
54
55 /* Order size using quicksort.  This implementation incorporates
56    four optimizations discussed in Sedgewick:
57
58    1. Non-recursive, using an explicit stack of pointer that store the
59       next array partition to sort.  To save time, this maximum amount
60       of space required to store an array of MAX_INT is allocated on the
61       stack.  Assuming a 32-bit integer, this needs only 32 *
62       sizeof (stack_node) == 136 bits.  Pretty cheap, actually.
63
64    2. Choose the pivot element using a median-of-three decision tree.
65       This reduces the probability of selecting a bad pivot value and
66       eliminates certain extraneous comparisons.
67
68    3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving
69       insertion sort to order the MAX_THRESH items within each partition.
70       This is a big win, since insertion sort is faster for small, mostly
71       sorted array segments.
72
73    4. The larger of the two sub-partitions is always pushed onto the
74       stack first, with the algorithm then concentrating on the
75       smaller partition.  This *guarantees* no more than log (n)
76       stack size is needed (actually O(1) in this case)! */
77
78 int qsort(base_ptr, total_elems, size, cmp)
79 char *base_ptr;
80 int total_elems;
81 int size;
82 int (*cmp) ();
83 {
84         /* Allocating SIZE bytes for a pivot buffer facilitates a better
85            algorithm below since we can do comparisons directly on the pivot. */
86         char *pivot_buffer = (char *)alloca(size);
87         int max_thresh = MAX_THRESH * size;
88
89         if (total_elems > MAX_THRESH) {
90                 char *lo = base_ptr;
91                 char *hi = lo + size * (total_elems - 1);
92                 stack_node stack[STACK_SIZE];   /* Largest size needed for 32-bit int!!! */
93                 stack_node *top = stack + 1;
94
95                 while (STACK_NOT_EMPTY) {
96                         char *left_ptr;
97                         char *right_ptr;
98                         {
99                                 char *pivot = pivot_buffer;
100                                 {
101                                         /* Select median value from among LO, MID, and HI. Rearrange
102                                            LO and HI so the three values are sorted. This lowers the
103                                            probability of picking a pathological pivot value and
104                                            skips a comparison for both the LEFT_PTR and RIGHT_PTR. */
105
106                                         char *mid =
107                                             lo + size * ((hi - lo) / size >> 1);
108
109                                         if (CMP(mid, lo) < 0)
110                                                 SWAP(mid, lo, size);
111                                         if (CMP(hi, mid) < 0)
112                                                 SWAP(mid, hi, size);
113                                         else
114                                                 goto jump_over;
115                                         if (CMP(mid, lo) < 0)
116                                                 SWAP(mid, lo, size);
117                                       jump_over:
118                                         COPY(pivot, mid, size);
119                                         pivot = pivot_buffer;
120                                 }
121                                 left_ptr = lo + size;
122                                 right_ptr = hi - size;
123
124                                 /* Here's the famous ``collapse the walls'' section of quicksort.
125                                    Gotta like those tight inner loops!  They are the main reason
126                                    that this algorithm runs much faster than others. */
127                                 do {
128                                         while (CMP(left_ptr, pivot) < 0)
129                                                 left_ptr += size;
130
131                                         while (CMP(pivot, right_ptr) < 0)
132                                                 right_ptr -= size;
133
134                                         if (left_ptr < right_ptr) {
135                                                 SWAP(left_ptr, right_ptr, size);
136                                                 left_ptr += size;
137                                                 right_ptr -= size;
138                                         } else if (left_ptr == right_ptr) {
139                                                 left_ptr += size;
140                                                 right_ptr -= size;
141                                                 break;
142                                         }
143                                 }
144                                 while (left_ptr <= right_ptr);
145
146                         }
147
148                         /* Set up pointers for next iteration.  First determine whether
149                            left and right partitions are below the threshold size. If so,
150                            ignore one or both.  Otherwise, push the larger partition's
151                            bounds on the stack and continue sorting the smaller one. */
152
153                         if ((right_ptr - lo) <= max_thresh) {
154                                 if ((hi - left_ptr) <= max_thresh)      /* Ignore both small partitions. */
155                                         POP(lo, hi);
156                                 else    /* Ignore small left partition. */
157                                         lo = left_ptr;
158                         } else if ((hi - left_ptr) <= max_thresh)       /* Ignore small right partition. */
159                                 hi = right_ptr;
160                         else if ((right_ptr - lo) > (hi - left_ptr)) {  /* Push larger left partition indices. */
161                                 PUSH(lo, right_ptr);
162                                 lo = left_ptr;
163                         } else {        /* Push larger right partition indices. */
164
165                                 PUSH(left_ptr, hi);
166                                 hi = right_ptr;
167                         }
168                 }
169         }
170
171         /* Once the BASE_PTR array is partially sorted by quicksort the rest
172            is completely sorted using insertion sort, since this is efficient
173            for partitions below MAX_THRESH size. BASE_PTR points to the beginning
174            of the array to sort, and END_PTR points at the very last element in
175            the array (*not* one beyond it!). */
176
177 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
178
179         {
180                 char *end_ptr = base_ptr + size * (total_elems - 1);
181                 char *run_ptr;
182                 char *tmp_ptr = base_ptr;
183                 char *thresh = MIN(end_ptr, base_ptr + max_thresh);
184
185                 /* Find smallest element in first threshold and place it at the
186                    array's beginning.  This is the smallest array element,
187                    and the operation speeds up insertion sort's inner loop. */
188
189                 for (run_ptr = tmp_ptr + size; run_ptr <= thresh;
190                      run_ptr += size)
191                         if (CMP(run_ptr, tmp_ptr) < 0)
192                                 tmp_ptr = run_ptr;
193
194                 if (tmp_ptr != base_ptr)
195                         SWAP(tmp_ptr, base_ptr, size);
196
197                 /* Insertion sort, running from left-hand-side up to `right-hand-side.'
198                    Pretty much straight out of the original GNU qsort routine. */
199
200                 for (run_ptr = base_ptr + size;
201                      (tmp_ptr = run_ptr += size) <= end_ptr;) {
202
203                         while (CMP(run_ptr, tmp_ptr -= size) < 0) ;
204
205                         if ((tmp_ptr += size) != run_ptr) {
206                                 char *trav;
207
208                                 for (trav = run_ptr + size; --trav >= run_ptr;) {
209                                         char c = *trav;
210                                         char *hi, *lo;
211
212                                         for (hi = lo = trav;
213                                              (lo -= size) >= tmp_ptr; hi = lo)
214                                                 *hi = *lo;
215                                         *hi = c;
216                                 }
217                         }
218
219                 }
220         }
221         return 1;
222 }