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)
5 This file is part of GNU CC.
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.
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.
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/>. */
20 /* Synched up with: FSF 19.28. */
26 /* Invoke the comparison function, returns either 0, < 0, or > 0. */
27 #define CMP(A,B) ((*cmp)((A),(B)))
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)
33 /* Copy SIZE bytes from item B to item A. */
34 #define COPY(A,B,SIZE) {int sz = (SIZE); do { *(A)++ = *(B)++; } while (--sz); }
36 /* This should be replaced by a standard ANSI macro. */
37 #define BYTES_PER_WORD 8
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)
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. */
49 /* Stack node declarations used to store unfulfilled partition obligations. */
55 /* Order size using quicksort. This implementation incorporates
56 four optimizations discussed in Sedgewick:
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.
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.
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.
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)! */
78 int qsort(base_ptr, total_elems, size, cmp)
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;
89 if (total_elems > MAX_THRESH) {
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;
95 while (STACK_NOT_EMPTY) {
99 char *pivot = pivot_buffer;
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. */
107 lo + size * ((hi - lo) / size >> 1);
109 if (CMP(mid, lo) < 0)
111 if (CMP(hi, mid) < 0)
115 if (CMP(mid, lo) < 0)
118 COPY(pivot, mid, size);
119 pivot = pivot_buffer;
121 left_ptr = lo + size;
122 right_ptr = hi - size;
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. */
128 while (CMP(left_ptr, pivot) < 0)
131 while (CMP(pivot, right_ptr) < 0)
134 if (left_ptr < right_ptr) {
135 SWAP(left_ptr, right_ptr, size);
138 } else if (left_ptr == right_ptr) {
144 while (left_ptr <= right_ptr);
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. */
153 if ((right_ptr - lo) <= max_thresh) {
154 if ((hi - left_ptr) <= max_thresh) /* Ignore both small partitions. */
156 else /* Ignore small left partition. */
158 } else if ((hi - left_ptr) <= max_thresh) /* Ignore small right partition. */
160 else if ((right_ptr - lo) > (hi - left_ptr)) { /* Push larger left partition indices. */
163 } else { /* Push larger right partition indices. */
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!). */
177 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
180 char *end_ptr = base_ptr + size * (total_elems - 1);
182 char *tmp_ptr = base_ptr;
183 char *thresh = MIN(end_ptr, base_ptr + max_thresh);
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. */
189 for (run_ptr = tmp_ptr + size; run_ptr <= thresh;
191 if (CMP(run_ptr, tmp_ptr) < 0)
194 if (tmp_ptr != base_ptr)
195 SWAP(tmp_ptr, base_ptr, size);
197 /* Insertion sort, running from left-hand-side up to `right-hand-side.'
198 Pretty much straight out of the original GNU qsort routine. */
200 for (run_ptr = base_ptr + size;
201 (tmp_ptr = run_ptr += size) <= end_ptr;) {
203 while (CMP(run_ptr, tmp_ptr -= size) < 0) ;
205 if ((tmp_ptr += size) != run_ptr) {
208 for (trav = run_ptr + size; --trav >= run_ptr;) {
213 (lo -= size) >= tmp_ptr; hi = lo)