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