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