Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[dragonfly.git] / lib / libcr / stdlib / radixsort.c
1 /*-
2  * Copyright (c) 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Peter McIlroy and by Dan Bernstein at New York University,
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * @(#)radixsort.c      8.2 (Berkeley) 4/28/95
37  */
38
39 /*
40  * Radixsort routines.
41  *
42  * Program r_sort_a() is unstable but uses O(logN) extra memory for a stack.
43  * Use radixsort(a, n, trace, endchar) for this case.
44  *
45  * For stable sorting (using N extra pointers) use sradixsort(), which calls
46  * r_sort_b().
47  *
48  * For a description of this code, see D. McIlroy, P. McIlroy, K. Bostic,
49  * "Engineering Radix Sort".
50  */
51
52 #include <sys/types.h>
53 #include <stdlib.h>
54 #include <stddef.h>
55 #include <errno.h>
56
57 typedef struct {
58         const u_char **sa;
59         int sn, si;
60 } stack;
61
62 static inline void simplesort
63             __P((const u_char **, int, int, const u_char *, u_int));
64 static void r_sort_a __P((const u_char **, int, int, const u_char *, u_int));
65 static void r_sort_b __P((const u_char **,
66             const u_char **, int, int, const u_char *, u_int));
67
68 #define THRESHOLD       20              /* Divert to simplesort(). */
69 #define SIZE            512             /* Default stack size. */
70
71 #define SETUP {                                                         \
72         if (tab == NULL) {                                              \
73                 tr = tr0;                                               \
74                 for (c = 0; c < endch; c++)                             \
75                         tr0[c] = c + 1;                                 \
76                 tr0[c] = 0;                                             \
77                 for (c++; c < 256; c++)                                 \
78                         tr0[c] = c;                                     \
79                 endch = 0;                                              \
80         } else {                                                        \
81                 endch = tab[endch];                                     \
82                 tr = tab;                                               \
83                 if (endch != 0 && endch != 255) {                       \
84                         errno = EINVAL;                                 \
85                         return (-1);                                    \
86                 }                                                       \
87         }                                                               \
88 }
89
90 int
91 radixsort(a, n, tab, endch)
92         const u_char **a, *tab;
93         int n;
94         u_int endch;
95 {
96         const u_char *tr;
97         int c;
98         u_char tr0[256];
99
100         SETUP;
101         r_sort_a(a, n, 0, tr, endch);
102         return (0);
103 }
104
105 int
106 sradixsort(a, n, tab, endch)
107         const u_char **a, *tab;
108         int n;
109         u_int endch;
110 {
111         const u_char *tr, **ta;
112         int c;
113         u_char tr0[256];
114
115         SETUP;
116         if (n < THRESHOLD)
117                 simplesort(a, n, 0, tr, endch);
118         else {
119                 if ((ta = malloc(n * sizeof(a))) == NULL)
120                         return (-1);
121                 r_sort_b(a, ta, n, 0, tr, endch);
122                 free(ta);
123         }
124         return (0);
125 }
126
127 #define empty(s)        (s >= sp)
128 #define pop(a, n, i)    a = (--sp)->sa, n = sp->sn, i = sp->si
129 #define push(a, n, i)   sp->sa = a, sp->sn = n, (sp++)->si = i
130 #define swap(a, b, t)   t = a, a = b, b = t
131
132 /* Unstable, in-place sort. */
133 static void
134 r_sort_a(a, n, i, tr, endch)
135         const u_char **a;
136         int n, i;
137         const u_char *tr;
138         u_int endch;
139 {
140         static int count[256], nc, bmin;
141         register int c;
142         register const u_char **ak, *r;
143         stack s[SIZE], *sp, *sp0, *sp1, temp;
144         int *cp, bigc;
145         const u_char **an, *t, **aj, **top[256];
146
147         /* Set up stack. */
148         sp = s;
149         push(a, n, i);
150         while (!empty(s)) {
151                 pop(a, n, i);
152                 if (n < THRESHOLD) {
153                         simplesort(a, n, i, tr, endch);
154                         continue;
155                 }
156                 an = a + n;
157
158                 /* Make character histogram. */
159                 if (nc == 0) {
160                         bmin = 255;     /* First occupied bin, excluding eos. */
161                         for (ak = a; ak < an;) {
162                                 c = tr[(*ak++)[i]];
163                                 if (++count[c] == 1 && c != endch) {
164                                         if (c < bmin)
165                                                 bmin = c;
166                                         nc++;
167                                 }
168                         }
169                         if (sp + nc > s + SIZE) {       /* Get more stack. */
170                                 r_sort_a(a, n, i, tr, endch);
171                                 continue;
172                         }
173                 }
174
175                 /*
176                  * Set top[]; push incompletely sorted bins onto stack.
177                  * top[] = pointers to last out-of-place element in bins.
178                  * count[] = counts of elements in bins.
179                  * Before permuting: top[c-1] + count[c] = top[c];
180                  * during deal: top[c] counts down to top[c-1].
181                  */
182                 sp0 = sp1 = sp;         /* Stack position of biggest bin. */
183                 bigc = 2;               /* Size of biggest bin. */
184                 if (endch == 0)         /* Special case: set top[eos]. */
185                         top[0] = ak = a + count[0];
186                 else {
187                         ak = a;
188                         top[255] = an;
189                 }
190                 for (cp = count + bmin; nc > 0; cp++) {
191                         while (*cp == 0)        /* Find next non-empty pile. */
192                                 cp++;
193                         if (*cp > 1) {
194                                 if (*cp > bigc) {
195                                         bigc = *cp;
196                                         sp1 = sp;
197                                 }
198                                 push(ak, *cp, i+1);
199                         }
200                         top[cp-count] = ak += *cp;
201                         nc--;
202                 }
203                 swap(*sp0, *sp1, temp); /* Play it safe -- biggest bin last. */
204
205                 /*
206                  * Permute misplacements home.  Already home: everything
207                  * before aj, and in bin[c], items from top[c] on.
208                  * Inner loop:
209                  *      r = next element to put in place;
210                  *      ak = top[r[i]] = location to put the next element.
211                  *      aj = bottom of 1st disordered bin.
212                  * Outer loop:
213                  *      Once the 1st disordered bin is done, ie. aj >= ak,
214                  *      aj<-aj + count[c] connects the bins in a linked list;
215                  *      reset count[c].
216                  */
217                 for (aj = a; aj < an;  *aj = r, aj += count[c], count[c] = 0)
218                         for (r = *aj;  aj < (ak = --top[c = tr[r[i]]]);)
219                                 swap(*ak, r, t);
220         }
221 }
222
223 /* Stable sort, requiring additional memory. */
224 static void
225 r_sort_b(a, ta, n, i, tr, endch)
226         const u_char **a, **ta;
227         int n, i;
228         const u_char *tr;
229         u_int endch;
230 {
231         static int count[256], nc, bmin;
232         register int c;
233         register const u_char **ak, **ai;
234         stack s[512], *sp, *sp0, *sp1, temp;
235         const u_char **top[256];
236         int *cp, bigc;
237
238         sp = s;
239         push(a, n, i);
240         while (!empty(s)) {
241                 pop(a, n, i);
242                 if (n < THRESHOLD) {
243                         simplesort(a, n, i, tr, endch);
244                         continue;
245                 }
246
247                 if (nc == 0) {
248                         bmin = 255;
249                         for (ak = a + n; --ak >= a;) {
250                                 c = tr[(*ak)[i]];
251                                 if (++count[c] == 1 && c != endch) {
252                                         if (c < bmin)
253                                                 bmin = c;
254                                         nc++;
255                                 }
256                         }
257                         if (sp + nc > s + SIZE) {
258                                 r_sort_b(a, ta, n, i, tr, endch);
259                                 continue;
260                         }
261                 }
262
263                 sp0 = sp1 = sp;
264                 bigc = 2;
265                 if (endch == 0) {
266                         top[0] = ak = a + count[0];
267                         count[0] = 0;
268                 } else {
269                         ak = a;
270                         top[255] = a + n;
271                         count[255] = 0;
272                 }
273                 for (cp = count + bmin; nc > 0; cp++) {
274                         while (*cp == 0)
275                                 cp++;
276                         if ((c = *cp) > 1) {
277                                 if (c > bigc) {
278                                         bigc = c;
279                                         sp1 = sp;
280                                 }
281                                 push(ak, c, i+1);
282                         }
283                         top[cp-count] = ak += c;
284                         *cp = 0;                        /* Reset count[]. */
285                         nc--;
286                 }
287                 swap(*sp0, *sp1, temp);
288
289                 for (ak = ta + n, ai = a+n; ak > ta;)   /* Copy to temp. */
290                         *--ak = *--ai;
291                 for (ak = ta+n; --ak >= ta;)            /* Deal to piles. */
292                         *--top[tr[(*ak)[i]]] = *ak;
293         }
294 }
295
296 static inline void
297 simplesort(a, n, b, tr, endch)  /* insertion sort */
298         register const u_char **a;
299         int n, b;
300         register const u_char *tr;
301         u_int endch;
302 {
303         register u_char ch;
304         const u_char  **ak, **ai, *s, *t;
305
306         for (ak = a+1; --n >= 1; ak++)
307                 for (ai = ak; ai > a; ai--) {
308                         for (s = ai[0] + b, t = ai[-1] + b;
309                             (ch = tr[*s]) != endch; s++, t++)
310                                 if (ch != tr[*t])
311                                         break;
312                         if (ch >= tr[*t])
313                                 break;
314                         swap(ai[0], ai[-1], s);
315                 }
316 }