r19955: I'll leave that to others. I *knew* I should not have touchec this
[Samba.git] / source / lib / ldb / common / qsort.c
blobef7be2c14ecb170bc5119ac4cb4b99a0829fafc8
1 /* Copyright (C) 1991,1992,1996,1997,1999,2004 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3 Written by Douglas C. Schmidt (schmidt@ics.uci.edu).
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.
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.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, write to the Free
17 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
18 02111-1307 USA. */
20 /* If you consider tuning this algorithm, you should consult first:
21 Engineering a sort function; Jon Bentley and M. Douglas McIlroy;
22 Software - Practice and Experience; Vol. 23 (11), 1249-1265, 1993. */
24 /* Modified to be used in samba4 by
25 * Simo Sorce <idra@samba.org> 2005
28 #include "includes.h"
29 #include "ldb/include/includes.h"
31 /* Byte-wise swap two items of size SIZE. */
32 #define SWAP(a, b, size) \
33 do \
34 { \
35 register size_t __size = (size); \
36 register char *__a = (a), *__b = (b); \
37 do \
38 { \
39 char __tmp = *__a; \
40 *__a++ = *__b; \
41 *__b++ = __tmp; \
42 } while (--__size > 0); \
43 } while (0)
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
49 /* Stack node declarations used to store unfulfilled partition obligations. */
50 typedef struct
52 char *lo;
53 char *hi;
54 } stack_node;
56 /* The next 4 #defines implement a very fast in-line stack abstraction. */
57 /* The stack needs log (total_elements) entries (we could even subtract
58 log(MAX_THRESH)). Since total_elements has type size_t, we get as
59 upper bound for log (total_elements):
60 bits per byte (CHAR_BIT) * sizeof(size_t). */
61 #ifndef CHAR_BIT
62 #define CHAR_BIT 8
63 #endif
64 #define STACK_SIZE (CHAR_BIT * sizeof(size_t))
65 #define PUSH(low, high) ((void) ((top->lo = (low)), (top->hi = (high)), ++top))
66 #define POP(low, high) ((void) (--top, (low = top->lo), (high = top->hi)))
67 #define STACK_NOT_EMPTY (stack < top)
70 /* Order size using quicksort. This implementation incorporates
71 four optimizations discussed in Sedgewick:
73 1. Non-recursive, using an explicit stack of pointer that store the
74 next array partition to sort. To save time, this maximum amount
75 of space required to store an array of SIZE_MAX is allocated on the
76 stack. Assuming a 32-bit (64 bit) integer for size_t, this needs
77 only 32 * sizeof(stack_node) == 256 bytes (for 64 bit: 1024 bytes).
78 Pretty cheap, actually.
80 2. Chose the pivot element using a median-of-three decision tree.
81 This reduces the probability of selecting a bad pivot value and
82 eliminates certain extraneous comparisons.
84 3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving
85 insertion sort to order the MAX_THRESH items within each partition.
86 This is a big win, since insertion sort is faster for small, mostly
87 sorted array segments.
89 4. The larger of the two sub-partitions is always pushed onto the
90 stack first, with the algorithm then concentrating on the
91 smaller partition. This *guarantees* no more than log (total_elems)
92 stack size is needed (actually O(1) in this case)! */
94 void ldb_qsort (void *const pbase, size_t total_elems, size_t size,
95 void *opaque, ldb_qsort_cmp_fn_t cmp)
97 register char *base_ptr = (char *) pbase;
99 const size_t max_thresh = MAX_THRESH * size;
101 if (total_elems == 0)
102 /* Avoid lossage with unsigned arithmetic below. */
103 return;
105 if (total_elems > MAX_THRESH)
107 char *lo = base_ptr;
108 char *hi = &lo[size * (total_elems - 1)];
109 stack_node stack[STACK_SIZE];
110 stack_node *top = stack;
112 PUSH (NULL, NULL);
114 while (STACK_NOT_EMPTY)
116 char *left_ptr;
117 char *right_ptr;
119 /* Select median value from among LO, MID, and HI. Rearrange
120 LO and HI so the three values are sorted. This lowers the
121 probability of picking a pathological pivot value and
122 skips a comparison for both the LEFT_PTR and RIGHT_PTR in
123 the while loops. */
125 char *mid = lo + size * ((hi - lo) / size >> 1);
127 if ((*cmp) ((void *) mid, (void *) lo, opaque) < 0)
128 SWAP (mid, lo, size);
129 if ((*cmp) ((void *) hi, (void *) mid, opaque) < 0)
130 SWAP (mid, hi, size);
131 else
132 goto jump_over;
133 if ((*cmp) ((void *) mid, (void *) lo, opaque) < 0)
134 SWAP (mid, lo, size);
135 jump_over:;
137 left_ptr = lo + size;
138 right_ptr = hi - size;
140 /* Here's the famous ``collapse the walls'' section of quicksort.
141 Gotta like those tight inner loops! They are the main reason
142 that this algorithm runs much faster than others. */
145 while ((*cmp) ((void *) left_ptr, (void *) mid, opaque) < 0)
146 left_ptr += size;
148 while ((*cmp) ((void *) mid, (void *) right_ptr, opaque) < 0)
149 right_ptr -= size;
151 if (left_ptr < right_ptr)
153 SWAP (left_ptr, right_ptr, size);
154 if (mid == left_ptr)
155 mid = right_ptr;
156 else if (mid == right_ptr)
157 mid = left_ptr;
158 left_ptr += size;
159 right_ptr -= size;
161 else if (left_ptr == right_ptr)
163 left_ptr += size;
164 right_ptr -= size;
165 break;
168 while (left_ptr <= right_ptr);
170 /* Set up pointers for next iteration. First determine whether
171 left and right partitions are below the threshold size. If so,
172 ignore one or both. Otherwise, push the larger partition's
173 bounds on the stack and continue sorting the smaller one. */
175 if ((size_t) (right_ptr - lo) <= max_thresh)
177 if ((size_t) (hi - left_ptr) <= max_thresh)
178 /* Ignore both small partitions. */
179 POP (lo, hi);
180 else
181 /* Ignore small left partition. */
182 lo = left_ptr;
184 else if ((size_t) (hi - left_ptr) <= max_thresh)
185 /* Ignore small right partition. */
186 hi = right_ptr;
187 else if ((right_ptr - lo) > (hi - left_ptr))
189 /* Push larger left partition indices. */
190 PUSH (lo, right_ptr);
191 lo = left_ptr;
193 else
195 /* Push larger right partition indices. */
196 PUSH (left_ptr, hi);
197 hi = right_ptr;
202 /* Once the BASE_PTR array is partially sorted by quicksort the rest
203 is completely sorted using insertion sort, since this is efficient
204 for partitions below MAX_THRESH size. BASE_PTR points to the beginning
205 of the array to sort, and END_PTR points at the very last element in
206 the array (*not* one beyond it!). */
208 #define min(x, y) ((x) < (y) ? (x) : (y))
211 char *const end_ptr = &base_ptr[size * (total_elems - 1)];
212 char *tmp_ptr = base_ptr;
213 char *thresh = min(end_ptr, base_ptr + max_thresh);
214 register char *run_ptr;
216 /* Find smallest element in first threshold and place it at the
217 array's beginning. This is the smallest array element,
218 and the operation speeds up insertion sort's inner loop. */
220 for (run_ptr = tmp_ptr + size; run_ptr <= thresh; run_ptr += size)
221 if ((*cmp) ((void *) run_ptr, (void *) tmp_ptr, opaque) < 0)
222 tmp_ptr = run_ptr;
224 if (tmp_ptr != base_ptr)
225 SWAP (tmp_ptr, base_ptr, size);
227 /* Insertion sort, running from left-hand-side up to right-hand-side. */
229 run_ptr = base_ptr + size;
230 while ((run_ptr += size) <= end_ptr)
232 tmp_ptr = run_ptr - size;
233 while ((*cmp) ((void *) run_ptr, (void *) tmp_ptr, opaque) < 0)
234 tmp_ptr -= size;
236 tmp_ptr += size;
237 if (tmp_ptr != run_ptr)
239 char *trav;
241 trav = run_ptr + size;
242 while (--trav >= run_ptr)
244 char c = *trav;
245 char *hi, *lo;
247 for (hi = lo = trav; (lo -= size) >= tmp_ptr; hi = lo)
248 *hi = *lo;
249 *hi = c;