1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1991, 1992, 1996, 1997 Free Software Foundation, Inc.
3 * Copyright (C) 2000 Eazel, Inc.
4 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the
18 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 * Boston, MA 02111-1307, USA.
23 * This file was originally part of the GNU C Library, and was modified to allow
24 * user data to be passed in to the sorting function.
26 * Written by Douglas C. Schmidt (schmidt@ics.uci.edu).
27 * Modified by Maciej Stachowiak (mjs@eazel.com)
29 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
30 * file for a list of people on the GLib Team. See the ChangeLog
31 * files for a list of changes. These files are distributed with GLib
32 * at ftp://ftp.gtk.org/pub/gtk/.
43 /* Byte-wise swap two items of size SIZE. */
44 #define SWAP(a, b, size) \
47 register size_t __size = (size); \
48 register char *__a = (a), *__b = (b); \
54 } while (--__size > 0); \
57 /* Discontinue quicksort algorithm when partition gets below this size.
58 This particular magic number was chosen to work best on a Sun 4/260. */
61 /* Stack node declarations used to store unfulfilled partition obligations. */
69 /* The next 4 #defines implement a very fast in-line stack abstraction. */
70 #define STACK_SIZE (8 * sizeof(unsigned long int))
71 #define PUSH(low, high) ((void) ((top->lo = (low)), (top->hi = (high)), ++top))
72 #define POP(low, high) ((void) (--top, (low = top->lo), (high = top->hi)))
73 #define STACK_NOT_EMPTY (stack < top)
76 /* Order size using quicksort. This implementation incorporates
77 * four optimizations discussed in Sedgewick:
79 * 1. Non-recursive, using an explicit stack of pointer that store the next
80 * array partition to sort. To save time, this maximum amount of space
81 * required to store an array of MAX_INT is allocated on the stack. Assuming
82 * a 32-bit integer, this needs only 32 * sizeof(stack_node) == 136 bits.
83 * Pretty cheap, actually.
85 * 2. Chose the pivot element using a median-of-three decision tree. This
86 * reduces the probability of selecting a bad pivot value and eliminates
87 * certain * extraneous comparisons.
89 * 3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving insertion
90 * sort to order the MAX_THRESH items within each partition. This is a big
91 * win, since insertion sort is faster for small, mostly sorted array
94 * 4. The larger of the two sub-partitions is always pushed onto the stack
95 * first, with the algorithm then concentrating on the smaller partition.
96 * This *guarantees* no more than log (n) stack size is needed (actually O(1)
102 * @pbase: start of array to sort
103 * @total_elems: elements in the array
104 * @size: size of each element
105 * @compare_func: function to compare elements
106 * @user_data: data to pass to @compare_func
108 * This is just like the standard C qsort() function, but
109 * the comparison routine accepts a user data argument.
113 g_qsort_with_data (gconstpointer pbase,
116 GCompareDataFunc compare_func,
119 register char *base_ptr = (char *) pbase;
121 /* Allocating SIZE bytes for a pivot buffer facilitates a better
122 * algorithm below since we can do comparisons directly on the pivot.
124 char *pivot_buffer = (char *) g_alloca (size);
125 const size_t max_thresh = MAX_THRESH * size;
127 g_return_if_fail (total_elems >= 0);
128 g_return_if_fail (pbase != NULL || total_elems == 0);
129 g_return_if_fail (compare_func != NULL);
131 if (total_elems == 0)
134 if (total_elems > MAX_THRESH)
137 char *hi = &lo[size * (total_elems - 1)];
138 /* Largest size needed for 32-bit int!!! */
139 stack_node stack[STACK_SIZE];
140 stack_node *top = stack + 1;
142 while (STACK_NOT_EMPTY)
147 char *pivot = pivot_buffer;
149 /* Select median value from among LO, MID, and HI. Rearrange
150 * LO and HI so the three values are sorted. This lowers the
151 * probability of picking a pathological pivot value and
152 * skips a comparison for both the LEFT_PTR and RIGHT_PTR. */
154 char *mid = lo + size * ((hi - lo) / size >> 1);
156 if ((*compare_func) ((void *) mid, (void *) lo, user_data) < 0)
157 SWAP (mid, lo, size);
158 if ((*compare_func) ((void *) hi, (void *) mid, user_data) < 0)
159 SWAP (mid, hi, size);
162 if ((*compare_func) ((void *) mid, (void *) lo, user_data) < 0)
163 SWAP (mid, lo, size);
165 memcpy (pivot, mid, size);
166 pivot = pivot_buffer;
168 left_ptr = lo + size;
169 right_ptr = hi - size;
171 /* Here's the famous ``collapse the walls'' section of quicksort.
172 * Gotta like those tight inner loops! They are the main reason
173 * that this algorithm runs much faster than others. */
176 while ((*compare_func)
177 ((void *) left_ptr, (void *) pivot,
181 while ((*compare_func)
182 ((void *) pivot, (void *) right_ptr,
186 if (left_ptr < right_ptr)
188 SWAP (left_ptr, right_ptr, size);
192 else if (left_ptr == right_ptr)
199 while (left_ptr <= right_ptr);
201 /* Set up pointers for next iteration. First determine whether
202 * left and right partitions are below the threshold size. If so,
203 * ignore one or both. Otherwise, push the larger partition's
204 * bounds on the stack and continue sorting the smaller one. */
206 if ((size_t) (right_ptr - lo) <= max_thresh)
208 if ((size_t) (hi - left_ptr) <= max_thresh)
209 /* Ignore both small partitions. */
212 /* Ignore small left partition. */
215 else if ((size_t) (hi - left_ptr) <= max_thresh)
216 /* Ignore small right partition. */
218 else if ((right_ptr - lo) > (hi - left_ptr))
220 /* Push larger left partition indices. */
221 PUSH (lo, right_ptr);
227 /* Push larger right partition indices. */
234 /* Once the BASE_PTR array is partially sorted by quicksort the rest
235 * is completely sorted using insertion sort, since this is efficient
236 * for partitions below MAX_THRESH size. BASE_PTR points to the beginning
237 * of the array to sort, and END_PTR points at the very last element in
238 * the array (*not* one beyond it!). */
241 char *const end_ptr = &base_ptr[size * (total_elems - 1)];
242 char *tmp_ptr = base_ptr;
243 char *thresh = MIN (end_ptr, base_ptr + max_thresh);
244 register char *run_ptr;
246 /* Find smallest element in first threshold and place it at the
247 * array's beginning. This is the smallest array element,
248 * and the operation speeds up insertion sort's inner loop. */
250 for (run_ptr = tmp_ptr + size; run_ptr <= thresh;
252 size) if ((*compare_func) ((void *) run_ptr, (void *) tmp_ptr,
256 if (tmp_ptr != base_ptr)
257 SWAP (tmp_ptr, base_ptr, size);
259 /* Insertion sort, running from left-hand-side up to right-hand-side. */
261 run_ptr = base_ptr + size;
262 while ((run_ptr += size) <= end_ptr)
264 tmp_ptr = run_ptr - size;
265 while ((*compare_func)
266 ((void *) run_ptr, (void *) tmp_ptr,
271 if (tmp_ptr != run_ptr)
275 trav = run_ptr + size;
276 while (--trav >= run_ptr)
282 (lo -= size) >= tmp_ptr; hi = lo)