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