Cosmetic rearrangement
[glib.git] / glib / gqsort.c
blobf0acecfe896eb6f94b3be7080ba03b8710ddaec2
1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1991, 1992, 1996, 1997,1999,2004 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/.
35 #include "config.h"
37 #include <limits.h>
38 #include <stdlib.h>
39 #include <string.h>
41 #include "gqsort.h"
43 #include "gtestutils.h"
45 /* Byte-wise swap two items of size SIZE. */
46 #define SWAP(a, b, size) \
47 do \
48 { \
49 register size_t __size = (size); \
50 register char *__a = (a), *__b = (b); \
51 do \
52 { \
53 char __tmp = *__a; \
54 *__a++ = *__b; \
55 *__b++ = __tmp; \
56 } while (--__size > 0); \
57 } while (0)
59 /* Discontinue quicksort algorithm when partition gets below this size.
60 This particular magic number was chosen to work best on a Sun 4/260. */
61 #define MAX_THRESH 4
63 /* Stack node declarations used to store unfulfilled partition obligations. */
64 typedef struct
66 char *lo;
67 char *hi;
68 } stack_node;
70 /* The next 4 #defines implement a very fast in-line stack abstraction. */
71 /* The stack needs log (total_elements) entries (we could even subtract
72 log(MAX_THRESH)). Since total_elements has type size_t, we get as
73 upper bound for log (total_elements):
74 bits per byte (CHAR_BIT) * sizeof(size_t). */
75 #define STACK_SIZE (CHAR_BIT * sizeof(size_t))
76 #define PUSH(low, high) ((void) ((top->lo = (low)), (top->hi = (high)), ++top))
77 #define POP(low, high) ((void) (--top, (low = top->lo), (high = top->hi)))
78 #define STACK_NOT_EMPTY (stack < top)
81 /* Order size using quicksort. This implementation incorporates
82 four optimizations discussed in Sedgewick:
84 1. Non-recursive, using an explicit stack of pointer that store the
85 next array partition to sort. To save time, this maximum amount
86 of space required to store an array of SIZE_MAX is allocated on the
87 stack. Assuming a 32-bit (64 bit) integer for size_t, this needs
88 only 32 * sizeof(stack_node) == 256 bytes (for 64 bit: 1024 bytes).
89 Pretty cheap, actually.
91 2. Chose the pivot element using a median-of-three decision tree.
92 This reduces the probability of selecting a bad pivot value and
93 eliminates certain extraneous comparisons.
95 3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving
96 insertion sort to order the MAX_THRESH items within each partition.
97 This is a big win, since insertion sort is faster for small, mostly
98 sorted array segments.
100 4. The larger of the two sub-partitions is always pushed onto the
101 stack first, with the algorithm then concentrating on the
102 smaller partition. This *guarantees* no more than log (total_elems)
103 stack size is needed (actually O(1) in this case)! */
106 * g_qsort_with_data:
107 * @pbase: start of array to sort
108 * @total_elems: elements in the array
109 * @size: size of each element
110 * @compare_func: function to compare elements
111 * @user_data: data to pass to @compare_func
113 * This is just like the standard C qsort() function, but
114 * the comparison routine accepts a user data argument.
117 void
118 g_qsort_with_data (gconstpointer pbase,
119 gint total_elems,
120 gsize size,
121 GCompareDataFunc compare_func,
122 gpointer user_data)
124 register char *base_ptr = (char *) pbase;
126 const size_t max_thresh = MAX_THRESH * size;
128 g_return_if_fail (total_elems >= 0);
129 g_return_if_fail (pbase != NULL || total_elems == 0);
130 g_return_if_fail (compare_func != NULL);
132 if (total_elems == 0)
133 /* Avoid lossage with unsigned arithmetic below. */
134 return;
136 if (total_elems > MAX_THRESH)
138 char *lo = base_ptr;
139 char *hi = &lo[size * (total_elems - 1)];
140 stack_node stack[STACK_SIZE];
141 stack_node *top = stack;
143 PUSH (NULL, NULL);
145 while (STACK_NOT_EMPTY)
147 char *left_ptr;
148 char *right_ptr;
150 /* Select median value from among LO, MID, and HI. Rearrange
151 LO and HI so the three values are sorted. This lowers the
152 probability of picking a pathological pivot value and
153 skips a comparison for both the LEFT_PTR and RIGHT_PTR in
154 the while loops. */
156 char *mid = lo + size * ((hi - lo) / size >> 1);
158 if ((*compare_func) ((void *) mid, (void *) lo, user_data) < 0)
159 SWAP (mid, lo, size);
160 if ((*compare_func) ((void *) hi, (void *) mid, user_data) < 0)
161 SWAP (mid, hi, size);
162 else
163 goto jump_over;
164 if ((*compare_func) ((void *) mid, (void *) lo, user_data) < 0)
165 SWAP (mid, lo, size);
166 jump_over:;
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) ((void *) left_ptr, (void *) mid, user_data) < 0)
177 left_ptr += size;
179 while ((*compare_func) ((void *) mid, (void *) right_ptr, user_data) < 0)
180 right_ptr -= size;
182 if (left_ptr < right_ptr)
184 SWAP (left_ptr, right_ptr, size);
185 if (mid == left_ptr)
186 mid = right_ptr;
187 else if (mid == right_ptr)
188 mid = left_ptr;
189 left_ptr += size;
190 right_ptr -= size;
192 else if (left_ptr == right_ptr)
194 left_ptr += size;
195 right_ptr -= size;
196 break;
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. */
210 POP (lo, hi);
211 else
212 /* Ignore small left partition. */
213 lo = left_ptr;
215 else if ((size_t) (hi - left_ptr) <= max_thresh)
216 /* Ignore small right partition. */
217 hi = right_ptr;
218 else if ((right_ptr - lo) > (hi - left_ptr))
220 /* Push larger left partition indices. */
221 PUSH (lo, right_ptr);
222 lo = left_ptr;
224 else
226 /* Push larger right partition indices. */
227 PUSH (left_ptr, hi);
228 hi = right_ptr;
233 /* Once the BASE_PTR array is partially sorted by quicksort the rest
234 is completely sorted using insertion sort, since this is efficient
235 for partitions below MAX_THRESH size. BASE_PTR points to the beginning
236 of the array to sort, and END_PTR points at the very last element in
237 the array (*not* one beyond it!). */
239 #define min(x, y) ((x) < (y) ? (x) : (y))
242 char *const end_ptr = &base_ptr[size * (total_elems - 1)];
243 char *tmp_ptr = base_ptr;
244 char *thresh = min(end_ptr, base_ptr + max_thresh);
245 register char *run_ptr;
247 /* Find smallest element in first threshold and place it at the
248 array's beginning. This is the smallest array element,
249 and the operation speeds up insertion sort's inner loop. */
251 for (run_ptr = tmp_ptr + size; run_ptr <= thresh; run_ptr += size)
252 if ((*compare_func) ((void *) run_ptr, (void *) tmp_ptr, user_data) < 0)
253 tmp_ptr = run_ptr;
255 if (tmp_ptr != base_ptr)
256 SWAP (tmp_ptr, base_ptr, size);
258 /* Insertion sort, running from left-hand-side up to right-hand-side. */
260 run_ptr = base_ptr + size;
261 while ((run_ptr += size) <= end_ptr)
263 tmp_ptr = run_ptr - size;
264 while ((*compare_func) ((void *) run_ptr, (void *) tmp_ptr, user_data) < 0)
265 tmp_ptr -= size;
267 tmp_ptr += size;
268 if (tmp_ptr != run_ptr)
270 char *trav;
272 trav = run_ptr + size;
273 while (--trav >= run_ptr)
275 char c = *trav;
276 char *hi, *lo;
278 for (hi = lo = trav; (lo -= size) >= tmp_ptr; hi = lo)
279 *hi = *lo;
280 *hi = c;