Clean up g_thread_yield implementation
[platform/upstream/glib.git] / glib / gqsort.c
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
5  *
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.
10  *
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.
15  *
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.
20  */
21
22 /*
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.
25  *
26  * Written by Douglas C. Schmidt (schmidt@ics.uci.edu).
27  * Modified by Maciej Stachowiak (mjs@eazel.com)
28  *
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/.
33  */
34
35 #include "config.h"
36
37 #include <limits.h>
38 #include <stdlib.h>
39 #include <string.h>
40
41 #include "gqsort.h"
42
43 #include "gtestutils.h"
44
45 #ifdef HAVE_QSORT_R
46
47 /**
48  * g_qsort_with_data:
49  * @pbase: start of array to sort
50  * @total_elems: elements in the array
51  * @size: size of each element
52  * @compare_func: function to compare elements
53  * @user_data: data to pass to @compare_func
54  *
55  * This is just like the standard C qsort() function, but
56  * the comparison routine accepts a user data argument.
57  */
58 void
59 g_qsort_with_data (gconstpointer    pbase,
60                    gint             total_elems,
61                    gsize            size,
62                    GCompareDataFunc compare_func,
63                    gpointer         user_data)
64 {
65   qsort_r ((gpointer)pbase, total_elems, size, compare_func, user_data);
66 }
67
68 #else
69
70 /* Byte-wise swap two items of size SIZE. */
71 #define SWAP(a, b, size)                                                      \
72   do                                                                          \
73     {                                                                         \
74       register size_t __size = (size);                                        \
75       register char *__a = (a), *__b = (b);                                   \
76       do                                                                      \
77         {                                                                     \
78           char __tmp = *__a;                                                  \
79           *__a++ = *__b;                                                      \
80           *__b++ = __tmp;                                                     \
81         } while (--__size > 0);                                               \
82     } while (0)
83
84 /* Discontinue quicksort algorithm when partition gets below this size.
85    This particular magic number was chosen to work best on a Sun 4/260. */
86 #define MAX_THRESH 4
87
88 /* Stack node declarations used to store unfulfilled partition obligations. */
89 typedef struct
90   {
91     char *lo;
92     char *hi;
93   } stack_node;
94
95 /* The next 4 #defines implement a very fast in-line stack abstraction. */
96 /* The stack needs log (total_elements) entries (we could even subtract
97    log(MAX_THRESH)).  Since total_elements has type size_t, we get as
98    upper bound for log (total_elements):
99    bits per byte (CHAR_BIT) * sizeof(size_t).  */
100 #define STACK_SIZE      (CHAR_BIT * sizeof(size_t))
101 #define PUSH(low, high) ((void) ((top->lo = (low)), (top->hi = (high)), ++top))
102 #define POP(low, high)  ((void) (--top, (low = top->lo), (high = top->hi)))
103 #define STACK_NOT_EMPTY (stack < top)
104
105
106 /* Order size using quicksort.  This implementation incorporates
107    four optimizations discussed in Sedgewick:
108
109    1. Non-recursive, using an explicit stack of pointer that store the
110       next array partition to sort.  To save time, this maximum amount
111       of space required to store an array of SIZE_MAX is allocated on the
112       stack.  Assuming a 32-bit (64 bit) integer for size_t, this needs
113       only 32 * sizeof(stack_node) == 256 bytes (for 64 bit: 1024 bytes).
114       Pretty cheap, actually.
115
116    2. Chose the pivot element using a median-of-three decision tree.
117       This reduces the probability of selecting a bad pivot value and
118       eliminates certain extraneous comparisons.
119
120    3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving
121       insertion sort to order the MAX_THRESH items within each partition.
122       This is a big win, since insertion sort is faster for small, mostly
123       sorted array segments.
124
125    4. The larger of the two sub-partitions is always pushed onto the
126       stack first, with the algorithm then concentrating on the
127       smaller partition.  This *guarantees* no more than log (total_elems)
128       stack size is needed (actually O(1) in this case)!  */
129
130 void
131 g_qsort_with_data (gconstpointer    pbase,
132                    gint             total_elems,
133                    gsize            size,
134                    GCompareDataFunc compare_func,
135                    gpointer         user_data)
136 {
137   register char *base_ptr = (char *) pbase;
138
139   const size_t max_thresh = MAX_THRESH * size;
140
141   g_return_if_fail (total_elems >= 0);
142   g_return_if_fail (pbase != NULL || total_elems == 0);
143   g_return_if_fail (compare_func != NULL);
144
145   if (total_elems == 0)
146     /* Avoid lossage with unsigned arithmetic below.  */
147     return;
148
149   if (total_elems > MAX_THRESH)
150     {
151       char *lo = base_ptr;
152       char *hi = &lo[size * (total_elems - 1)];
153       stack_node stack[STACK_SIZE];
154       stack_node *top = stack;
155
156       PUSH (NULL, NULL);
157
158       while (STACK_NOT_EMPTY)
159         {
160           char *left_ptr;
161           char *right_ptr;
162
163           /* Select median value from among LO, MID, and HI. Rearrange
164              LO and HI so the three values are sorted. This lowers the
165              probability of picking a pathological pivot value and
166              skips a comparison for both the LEFT_PTR and RIGHT_PTR in
167              the while loops. */
168
169           char *mid = lo + size * ((hi - lo) / size >> 1);
170
171           if ((*compare_func) ((void *) mid, (void *) lo, user_data) < 0)
172             SWAP (mid, lo, size);
173           if ((*compare_func) ((void *) hi, (void *) mid, user_data) < 0)
174             SWAP (mid, hi, size);
175           else
176             goto jump_over;
177           if ((*compare_func) ((void *) mid, (void *) lo, user_data) < 0)
178             SWAP (mid, lo, size);
179         jump_over:;
180
181           left_ptr  = lo + size;
182           right_ptr = hi - size;
183
184           /* Here's the famous ``collapse the walls'' section of quicksort.
185              Gotta like those tight inner loops!  They are the main reason
186              that this algorithm runs much faster than others. */
187           do
188             {
189               while ((*compare_func) ((void *) left_ptr, (void *) mid, user_data) < 0)
190                 left_ptr += size;
191
192               while ((*compare_func) ((void *) mid, (void *) right_ptr, user_data) < 0)
193                 right_ptr -= size;
194
195               if (left_ptr < right_ptr)
196                 {
197                   SWAP (left_ptr, right_ptr, size);
198                   if (mid == left_ptr)
199                     mid = right_ptr;
200                   else if (mid == right_ptr)
201                     mid = left_ptr;
202                   left_ptr += size;
203                   right_ptr -= size;
204                 }
205               else if (left_ptr == right_ptr)
206                 {
207                   left_ptr += size;
208                   right_ptr -= size;
209                   break;
210                 }
211             }
212           while (left_ptr <= right_ptr);
213
214           /* Set up pointers for next iteration.  First determine whether
215              left and right partitions are below the threshold size.  If so,
216              ignore one or both.  Otherwise, push the larger partition's
217              bounds on the stack and continue sorting the smaller one. */
218
219           if ((size_t) (right_ptr - lo) <= max_thresh)
220             {
221               if ((size_t) (hi - left_ptr) <= max_thresh)
222                 /* Ignore both small partitions. */
223                 POP (lo, hi);
224               else
225                 /* Ignore small left partition. */
226                 lo = left_ptr;
227             }
228           else if ((size_t) (hi - left_ptr) <= max_thresh)
229             /* Ignore small right partition. */
230             hi = right_ptr;
231           else if ((right_ptr - lo) > (hi - left_ptr))
232             {
233               /* Push larger left partition indices. */
234               PUSH (lo, right_ptr);
235               lo = left_ptr;
236             }
237           else
238             {
239               /* Push larger right partition indices. */
240               PUSH (left_ptr, hi);
241               hi = right_ptr;
242             }
243         }
244     }
245
246   /* Once the BASE_PTR array is partially sorted by quicksort the rest
247      is completely sorted using insertion sort, since this is efficient
248      for partitions below MAX_THRESH size. BASE_PTR points to the beginning
249      of the array to sort, and END_PTR points at the very last element in
250      the array (*not* one beyond it!). */
251
252 #define min(x, y) ((x) < (y) ? (x) : (y))
253
254   {
255     char *const end_ptr = &base_ptr[size * (total_elems - 1)];
256     char *tmp_ptr = base_ptr;
257     char *thresh = min(end_ptr, base_ptr + max_thresh);
258     register char *run_ptr;
259
260     /* Find smallest element in first threshold and place it at the
261        array's beginning.  This is the smallest array element,
262        and the operation speeds up insertion sort's inner loop. */
263
264     for (run_ptr = tmp_ptr + size; run_ptr <= thresh; run_ptr += size)
265       if ((*compare_func) ((void *) run_ptr, (void *) tmp_ptr, user_data) < 0)
266         tmp_ptr = run_ptr;
267
268     if (tmp_ptr != base_ptr)
269       SWAP (tmp_ptr, base_ptr, size);
270
271     /* Insertion sort, running from left-hand-side up to right-hand-side.  */
272
273     run_ptr = base_ptr + size;
274     while ((run_ptr += size) <= end_ptr)
275       {
276         tmp_ptr = run_ptr - size;
277         while ((*compare_func) ((void *) run_ptr, (void *) tmp_ptr, user_data) < 0)
278           tmp_ptr -= size;
279
280         tmp_ptr += size;
281         if (tmp_ptr != run_ptr)
282           {
283             char *trav;
284
285             trav = run_ptr + size;
286             while (--trav >= run_ptr)
287               {
288                 char c = *trav;
289                 char *hi, *lo;
290
291                 for (hi = lo = trav; (lo -= size) >= tmp_ptr; hi = lo)
292                   *hi = *lo;
293                 *hi = c;
294               }
295           }
296       }
297   }
298 }
299
300 #endif /* HAVE_QSORT_R */