xref: /netbsd-src/lib/libc/stdlib/radixsort.c (revision de4fa6c51a9708fc05f88b618fa6fad87c9508ec)
1 /*	$NetBSD: radixsort.c,v 1.18 2009/08/21 20:49:50 dsl 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.18 2009/08/21 20:49:50 dsl 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
75 	    __P((const u_char **, int, int, const u_char *, u_int));
76 static void r_sort_a __P((const u_char **, int, int, const u_char *, u_int));
77 static void r_sort_b __P((const u_char **,
78 	    const u_char **, int, int, const u_char *, u_int));
79 
80 #define	THRESHOLD	20		/* Divert to simplesort(). */
81 #define	SIZE		512		/* Default stack size. */
82 
83 #define SETUP {								\
84 	if (tab == NULL) {						\
85 		tr = tr0;						\
86 		for (c = 0; c < endch; c++)				\
87 			tr0[c] = c + 1;					\
88 		tr0[c] = 0;						\
89 		for (c++; c < 256; c++)					\
90 			tr0[c] = c;					\
91 		endch = 0;						\
92 	} else {							\
93 		endch = tab[endch];					\
94 		tr = tab;						\
95 		if (endch != 0 && endch != 255) {			\
96 			errno = EINVAL;					\
97 			return (-1);					\
98 		}							\
99 	}								\
100 }
101 
102 int
103 radixsort(a, n, tab, endch)
104 	const u_char **a, *tab;
105 	int n;
106 	u_int endch;
107 {
108 	const u_char *tr;
109 	u_int c;
110 	u_char tr0[256];
111 
112 	_DIAGASSERT(a != NULL);
113 
114 	SETUP;
115 	r_sort_a(a, n, 0, tr, endch);
116 	return (0);
117 }
118 
119 int
120 sradixsort(a, n, tab, endch)
121 	const u_char **a, *tab;
122 	int n;
123 	u_int endch;
124 {
125 	const u_char *tr, **ta;
126 	u_int c;
127 	u_char tr0[256];
128 
129 	_DIAGASSERT(a != NULL);
130 	if (a == NULL) {
131 		errno = EFAULT;
132 		return (-1);
133 	}
134 
135 	SETUP;
136 	if (n < THRESHOLD)
137 		simplesort(a, n, 0, tr, endch);
138 	else {
139 		if ((ta = malloc(n * sizeof(a))) == NULL)
140 			return (-1);
141 		r_sort_b(a, ta, n, 0, tr, endch);
142 		free(ta);
143 	}
144 	return (0);
145 }
146 
147 #define empty(s)	(s >= sp)
148 #define pop(a, n, i)	a = (--sp)->sa, n = sp->sn, i = sp->si
149 #define push(a, n, i)	sp->sa = a, sp->sn = n, (sp++)->si = i
150 #define swap(a, b, t)	t = a, a = b, b = t
151 
152 /* Unstable, in-place sort. */
153 static void
154 r_sort_a(a, n, i, tr, endch)
155 	const u_char **a;
156 	int n, i;
157 	const u_char *tr;
158 	u_int endch;
159 {
160 	static u_int count[256], nc, bmin;
161 	u_int c;
162 	const u_char **ak, *r;
163 	stack s[SIZE], *sp, *sp0, *sp1, temp;
164 	u_int *cp, bigc;
165 	const u_char **an, *t, **aj, **top[256];
166 
167 	_DIAGASSERT(a != NULL);
168 	_DIAGASSERT(tr != NULL);
169 
170 	/* Set up stack. */
171 	sp = s;
172 	push(a, n, i);
173 	while (!empty(s)) {
174 		pop(a, n, i);
175 		if (n < THRESHOLD) {
176 			simplesort(a, n, i, tr, endch);
177 			continue;
178 		}
179 		an = a + n;
180 
181 		/* Make character histogram. */
182 		if (nc == 0) {
183 			bmin = 255;	/* First occupied bin, excluding eos. */
184 			for (ak = a; ak < an;) {
185 				c = tr[(*ak++)[i]];
186 				if (++count[c] == 1 && c != endch) {
187 					if (c < bmin)
188 						bmin = c;
189 					nc++;
190 				}
191 			}
192 			if (sp + nc > s + SIZE) {	/* Get more stack. */
193 				r_sort_a(a, n, i, tr, endch);
194 				continue;
195 			}
196 		}
197 
198 		/*
199 		 * Set top[]; push incompletely sorted bins onto stack.
200 		 * top[] = pointers to last out-of-place element in bins.
201 		 * count[] = counts of elements in bins.
202 		 * Before permuting: top[c-1] + count[c] = top[c];
203 		 * during deal: top[c] counts down to top[c-1].
204 		 */
205 		sp0 = sp1 = sp;		/* Stack position of biggest bin. */
206 		bigc = 2;		/* Size of biggest bin. */
207 		if (endch == 0)		/* Special case: set top[eos]. */
208 			top[0] = ak = a + count[0];
209 		else {
210 			ak = a;
211 			top[255] = an;
212 		}
213 		for (cp = count + bmin; nc > 0; cp++) {
214 			while (*cp == 0)	/* Find next non-empty pile. */
215 				cp++;
216 			if (*cp > 1) {
217 				if (*cp > bigc) {
218 					bigc = *cp;
219 					sp1 = sp;
220 				}
221 				push(ak, *cp, i+1);
222 			}
223 			top[cp-count] = ak += *cp;
224 			nc--;
225 		}
226 		swap(*sp0, *sp1, temp);	/* Play it safe -- biggest bin last. */
227 
228 		/*
229 		 * Permute misplacements home.  Already home: everything
230 		 * before aj, and in bin[c], items from top[c] on.
231 		 * Inner loop:
232 		 *	r = next element to put in place;
233 		 *	ak = top[r[i]] = location to put the next element.
234 		 *	aj = bottom of 1st disordered bin.
235 		 * Outer loop:
236 		 *	Once the 1st disordered bin is done, ie. aj >= ak,
237 		 *	aj<-aj + count[c] connects the bins in a linked list;
238 		 *	reset count[c].
239 		 */
240 		for (aj = a; aj < an;  *aj = r, aj += count[c], count[c] = 0)
241 			for (r = *aj;  aj < (ak = --top[c = tr[r[i]]]);)
242 				swap(*ak, r, t);
243 	}
244 }
245 
246 /* Stable sort, requiring additional memory. */
247 static void
248 r_sort_b(a, ta, n, i, tr, endch)
249 	const u_char **a, **ta;
250 	int n, i;
251 	const u_char *tr;
252 	u_int endch;
253 {
254 	static u_int count[256], nc, bmin;
255 	u_int c;
256 	const u_char **ak, **ai;
257 	stack s[512], *sp, *sp0, *sp1, temp;
258 	const u_char **top[256];
259 	u_int *cp, bigc;
260 
261 	_DIAGASSERT(a != NULL);
262 	_DIAGASSERT(ta != NULL);
263 	_DIAGASSERT(tr != NULL);
264 
265 	sp = s;
266 	push(a, n, i);
267 	while (!empty(s)) {
268 		pop(a, n, i);
269 		if (n < THRESHOLD) {
270 			simplesort(a, n, i, tr, endch);
271 			continue;
272 		}
273 
274 		if (nc == 0) {
275 			bmin = 255;
276 			for (ak = a + n; --ak >= a;) {
277 				c = tr[(*ak)[i]];
278 				if (++count[c] == 1 && c != endch) {
279 					if (c < bmin)
280 						bmin = c;
281 					nc++;
282 				}
283 			}
284 			if (sp + nc > s + SIZE) {
285 				r_sort_b(a, ta, n, i, tr, endch);
286 				continue;
287 			}
288 		}
289 
290 		sp0 = sp1 = sp;
291 		bigc = 2;
292 		if (endch == 0) {
293 			top[0] = ak = a + count[0];
294 			count[0] = 0;
295 		} else {
296 			ak = a;
297 			top[255] = a + n;
298 			count[255] = 0;
299 		}
300 		for (cp = count + bmin; nc > 0; cp++) {
301 			while (*cp == 0)
302 				cp++;
303 			if ((c = *cp) > 1) {
304 				if (c > bigc) {
305 					bigc = c;
306 					sp1 = sp;
307 				}
308 				push(ak, c, i+1);
309 			}
310 			top[cp-count] = ak += c;
311 			*cp = 0;			/* Reset count[]. */
312 			nc--;
313 		}
314 		swap(*sp0, *sp1, temp);
315 
316 		for (ak = ta + n, ai = a+n; ak > ta;)	/* Copy to temp. */
317 			*--ak = *--ai;
318 		for (ak = ta+n; --ak >= ta;)		/* Deal to piles. */
319 			*--top[tr[(*ak)[i]]] = *ak;
320 	}
321 }
322 
323 static inline void
324 simplesort(a, n, b, tr, endch)	/* insertion sort */
325 	const u_char **a;
326 	int n, b;
327 	const u_char *tr;
328 	u_int endch;
329 {
330 	u_char ch;
331 	const u_char  **ak, **ai, *s, *t;
332 
333 	_DIAGASSERT(a != NULL);
334 	_DIAGASSERT(tr != NULL);
335 
336 	for (ak = a+1; --n >= 1; ak++)
337 		for (ai = ak; ai > a; ai--) {
338 			for (s = ai[0] + b, t = ai[-1] + b;
339 			    (ch = tr[*s]) != endch; s++, t++)
340 				if (ch != tr[*t])
341 					break;
342 			if (ch >= tr[*t])
343 				break;
344 			swap(ai[0], ai[-1], s);
345 		}
346 }
347