Add event to interrupt the server_loop.
[apps/pfixtools.git] / common / qsort.c
1 /* $Id: qsort.c,v 1.3 2003/04/11 12:31:46 mjt Exp $
2  * Adopted from GNU glibc by Mjt.
3  * See stdlib/qsort.c in glibc */
4
5 /* Copyright (C) 1991, 1992, 1996, 1997, 1999 Free Software Foundation, Inc.
6    This file is part of the GNU C Library.
7    Written by Douglas C. Schmidt (schmidt@ics.uci.edu).
8
9    The GNU C Library is free software; you can redistribute it and/or
10    modify it under the terms of the GNU Lesser General Public
11    License as published by the Free Software Foundation; either
12    version 2.1 of the License, or (at your option) any later version.
13
14    The GNU C Library is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17    Lesser General Public License for more details.
18
19    You should have received a copy of the GNU Lesser General Public
20    License along with the GNU C Library; if not, write to the Free
21    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
22    02111-1307 USA.  */
23
24 /* Usage:
25  * first, define the following:
26  *  QSORT_TYPE - type of array elements
27  *  QSORT_BASE - pointer to array
28  *  QSORT_NELT - number of elements in the array (must not be 0)
29  *  QSORT_LT - QSORT_LT(a,b) should return true if *a < *b
30  * and second, just #include this file into the place you want it.
31  * Some C code will be inserted into that place, to sort array defined
32  * by QSORT_TYPE, QSORT_BASE, QSORT_NELT and comparision routine QSORT_LT.
33  */
34
35 /* Swap two items pointed to by A and B using temporary buffer t. */
36 #define _QSORT_SWAP(a, b, t) ((void)((t = *a), (*a = *b), (*b = t)))
37
38 /* Discontinue quicksort algorithm when partition gets below this size.
39    This particular magic number was chosen to work best on a Sun 4/260. */
40 #define _QSORT_MAX_THRESH 4
41
42 /* Stack node declarations used to store unfulfilled partition obligations
43  * (inlined in QSORT).
44 typedef struct {
45   TYPE *_lo, *_hi;
46 } qsort_stack_node;
47  */
48
49 /* The next 4 #defines implement a very fast in-line stack abstraction. */
50 /* The stack needs log (total_elements) entries (we could even subtract
51    log(MAX_THRESH)).  Since total_elements has type unsigned, we get as
52    upper bound for log (total_elements):
53    bits per byte (CHAR_BIT) * sizeof(unsigned).  */
54 #define _QSORT_STACK_SIZE       (8 * sizeof(unsigned))
55 #define _QSORT_PUSH(top, low, high)     \
56         (((top->_lo = (low)), (top->_hi = (high)), ++top))
57 #define _QSORT_POP(low, high, top)      \
58         ((--top, (low = top->_lo), (high = top->_hi)))
59 #define _QSORT_STACK_NOT_EMPTY  (_stack < _top)
60
61
62 /* Order size using quicksort.  This implementation incorporates
63    four optimizations discussed in Sedgewick:
64
65    1. Non-recursive, using an explicit stack of pointer that store the
66       next array partition to sort.  To save time, this maximum amount
67       of space required to store an array of SIZE_MAX is allocated on the
68       stack.  Assuming a 32-bit (64 bit) integer for size_t, this needs
69       only 32 * sizeof(stack_node) == 256 bytes (for 64 bit: 1024 bytes).
70       Pretty cheap, actually.
71
72    2. Chose the pivot element using a median-of-three decision tree.
73       This reduces the probability of selecting a bad pivot value and
74       eliminates certain extraneous comparisons.
75
76    3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving
77       insertion sort to order the MAX_THRESH items within each partition.
78       This is a big win, since insertion sort is faster for small, mostly
79       sorted array segments.
80
81    4. The larger of the two sub-partitions is always pushed onto the
82       stack first, with the algorithm then concentrating on the
83       smaller partition.  This *guarantees* no more than log (total_elems)
84       stack size is needed (actually O(1) in this case)!  */
85
86
87 {
88   QSORT_TYPE *const _base = (QSORT_BASE);
89   const unsigned _elems = (QSORT_NELT);
90   QSORT_TYPE _hold;
91
92   if (_elems > _QSORT_MAX_THRESH) {
93     QSORT_TYPE *_lo = _base;
94     QSORT_TYPE *_hi = _lo + _elems - 1;
95     struct {
96       QSORT_TYPE *_hi, *_lo;
97     } _stack[_QSORT_STACK_SIZE], *_top = _stack + 1;
98
99     while (_QSORT_STACK_NOT_EMPTY) {
100       QSORT_TYPE *_left_ptr, *_right_ptr;
101
102       /* Select median value from among LO, MID, and HI. Rearrange
103          LO and HI so the three values are sorted. This lowers the
104          probability of picking a pathological pivot value and
105          skips a comparison for both the LEFT_PTR and RIGHT_PTR in
106          the while loops. */
107
108       QSORT_TYPE *_mid = _lo + ((_hi - _lo) >> 1);
109
110       if (QSORT_LT (_mid, _lo))
111         _QSORT_SWAP (_mid, _lo, _hold);
112       if (QSORT_LT (_hi, _mid))
113         _QSORT_SWAP (_mid, _hi, _hold);
114       else
115         goto _jump_over;
116       if (QSORT_LT (_mid, _lo))
117         _QSORT_SWAP (_mid, _lo, _hold);
118   _jump_over:;
119
120       _left_ptr  = _lo + 1;
121       _right_ptr = _hi - 1;
122
123       /* Here's the famous ``collapse the walls'' section of quicksort.
124          Gotta like those tight inner loops!  They are the main reason
125          that this algorithm runs much faster than others. */
126       do {
127         while (QSORT_LT (_left_ptr, _mid))
128          ++_left_ptr;
129
130         while (QSORT_LT (_mid, _right_ptr))
131           --_right_ptr;
132
133         if (_left_ptr < _right_ptr) {
134           _QSORT_SWAP (_left_ptr, _right_ptr, _hold);
135           if (_mid == _left_ptr)
136             _mid = _right_ptr;
137           else if (_mid == _right_ptr)
138             _mid = _left_ptr;
139           ++_left_ptr;
140           --_right_ptr;
141         }
142         else if (_left_ptr == _right_ptr) {
143           ++_left_ptr;
144           --_right_ptr;
145           break;
146         }
147       } while (_left_ptr <= _right_ptr);
148
149      /* Set up pointers for next iteration.  First determine whether
150         left and right partitions are below the threshold size.  If so,
151         ignore one or both.  Otherwise, push the larger partition's
152         bounds on the stack and continue sorting the smaller one. */
153
154       if (_right_ptr - _lo <= _QSORT_MAX_THRESH) {
155         if (_hi - _left_ptr <= _QSORT_MAX_THRESH)
156           /* Ignore both small partitions. */
157           _QSORT_POP (_lo, _hi, _top);
158         else
159           /* Ignore small left partition. */
160           _lo = _left_ptr;
161       }
162       else if (_hi - _left_ptr <= _QSORT_MAX_THRESH)
163         /* Ignore small right partition. */
164         _hi = _right_ptr;
165       else if (_right_ptr - _lo > _hi - _left_ptr) {
166         /* Push larger left partition indices. */
167         _QSORT_PUSH (_top, _lo, _right_ptr);
168         _lo = _left_ptr;
169       }
170       else {
171         /* Push larger right partition indices. */
172         _QSORT_PUSH (_top, _left_ptr, _hi);
173         _hi = _right_ptr;
174       }
175     }
176   }
177
178   /* Once the BASE array is partially sorted by quicksort the rest
179      is completely sorted using insertion sort, since this is efficient
180      for partitions below MAX_THRESH size. BASE points to the
181      beginning of the array to sort, and END_PTR points at the very
182      last element in the array (*not* one beyond it!). */
183
184
185   {
186     QSORT_TYPE *const _end_ptr = _base + _elems - 1;
187     QSORT_TYPE *_tmp_ptr = _base;
188     register QSORT_TYPE *_run_ptr;
189     QSORT_TYPE *_thresh;
190
191     _thresh = _base + _QSORT_MAX_THRESH;
192     if (_thresh > _end_ptr)
193       _thresh = _end_ptr;
194
195     /* Find smallest element in first threshold and place it at the
196        array's beginning.  This is the smallest array element,
197        and the operation speeds up insertion sort's inner loop. */
198
199     for (_run_ptr = _tmp_ptr + 1; _run_ptr <= _thresh; ++_run_ptr)
200       if (QSORT_LT (_run_ptr, _tmp_ptr))
201         _tmp_ptr = _run_ptr;
202
203     if (_tmp_ptr != _base)
204       _QSORT_SWAP (_tmp_ptr, _base, _hold);
205
206     /* Insertion sort, running from left-hand-side
207      * up to right-hand-side.  */
208
209     _run_ptr = _base + 1;
210     while (++_run_ptr <= _end_ptr) {
211       _tmp_ptr = _run_ptr - 1;
212       while (QSORT_LT (_run_ptr, _tmp_ptr))
213         --_tmp_ptr;
214
215       ++_tmp_ptr;
216       if (_tmp_ptr != _run_ptr) {
217         QSORT_TYPE *_trav = _run_ptr + 1;
218         while (--_trav >= _run_ptr) {
219           QSORT_TYPE *_hi, *_lo;
220           _hold = *_trav;
221
222           for (_hi = _lo = _trav; --_lo >= _tmp_ptr; _hi = _lo)
223             *_hi = *_lo;
224           *_hi = _hold;
225         }
226       }
227     }
228   }
229 }