xref: /freebsd/lib/libc/stdlib/radixsort.c (revision 3ff369fed2a08f32dda232c10470b949bef9489f)
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 
37 #if defined(LIBC_SCCS) && !defined(lint)
38 static char sccsid[] = "@(#)radixsort.c	8.2 (Berkeley) 4/28/95";
39 #endif /* LIBC_SCCS and not lint */
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42 
43 /*
44  * Radixsort routines.
45  *
46  * Program r_sort_a() is unstable but uses O(logN) extra memory for a stack.
47  * Use radixsort(a, n, trace, endchar) for this case.
48  *
49  * For stable sorting (using N extra pointers) use sradixsort(), which calls
50  * r_sort_b().
51  *
52  * For a description of this code, see D. McIlroy, P. McIlroy, K. Bostic,
53  * "Engineering Radix Sort".
54  */
55 
56 #include <sys/types.h>
57 #include <stdlib.h>
58 #include <stddef.h>
59 #include <errno.h>
60 
61 typedef struct {
62 	const u_char **sa;
63 	int sn, si;
64 } stack;
65 
66 static inline void simplesort
67 (const u_char **, int, int, const u_char *, u_int);
68 static void r_sort_a(const u_char **, int, int, const u_char *, u_int);
69 static void r_sort_b(const u_char **, const u_char **, int, int,
70     const u_char *, u_int);
71 
72 #define	THRESHOLD	20		/* Divert to simplesort(). */
73 #define	SIZE		512		/* Default stack size. */
74 
75 #define SETUP {								\
76 	if (tab == NULL) {						\
77 		tr = tr0;						\
78 		for (c = 0; c < endch; c++)				\
79 			tr0[c] = c + 1;					\
80 		tr0[c] = 0;						\
81 		for (c++; c < 256; c++)					\
82 			tr0[c] = c;					\
83 		endch = 0;						\
84 	} else {							\
85 		endch = tab[endch];					\
86 		tr = tab;						\
87 		if (endch != 0 && endch != 255) {			\
88 			errno = EINVAL;					\
89 			return (-1);					\
90 		}							\
91 	}								\
92 }
93 
94 int
95 radixsort(a, n, tab, endch)
96 	const u_char **a, *tab;
97 	int n;
98 	u_int endch;
99 {
100 	const u_char *tr;
101 	int c;
102 	u_char tr0[256];
103 
104 	SETUP;
105 	r_sort_a(a, n, 0, tr, endch);
106 	return (0);
107 }
108 
109 int
110 sradixsort(a, n, tab, endch)
111 	const u_char **a, *tab;
112 	int n;
113 	u_int endch;
114 {
115 	const u_char *tr, **ta;
116 	int c;
117 	u_char tr0[256];
118 
119 	SETUP;
120 	if (n < THRESHOLD)
121 		simplesort(a, n, 0, tr, endch);
122 	else {
123 		if ((ta = malloc(n * sizeof(a))) == NULL)
124 			return (-1);
125 		r_sort_b(a, ta, n, 0, tr, endch);
126 		free(ta);
127 	}
128 	return (0);
129 }
130 
131 #define empty(s)	(s >= sp)
132 #define pop(a, n, i)	a = (--sp)->sa, n = sp->sn, i = sp->si
133 #define push(a, n, i)	sp->sa = a, sp->sn = n, (sp++)->si = i
134 #define swap(a, b, t)	t = a, a = b, b = t
135 
136 /* Unstable, in-place sort. */
137 static void
138 r_sort_a(a, n, i, tr, endch)
139 	const u_char **a;
140 	int n, i;
141 	const u_char *tr;
142 	u_int endch;
143 {
144 	static int count[256], nc, bmin;
145 	int c;
146 	const u_char **ak, *r;
147 	stack s[SIZE], *sp, *sp0, *sp1, temp;
148 	int *cp, bigc;
149 	const u_char **an, *t, **aj, **top[256];
150 
151 	/* Set up stack. */
152 	sp = s;
153 	push(a, n, i);
154 	while (!empty(s)) {
155 		pop(a, n, i);
156 		if (n < THRESHOLD) {
157 			simplesort(a, n, i, tr, endch);
158 			continue;
159 		}
160 		an = a + n;
161 
162 		/* Make character histogram. */
163 		if (nc == 0) {
164 			bmin = 255;	/* First occupied bin, excluding eos. */
165 			for (ak = a; ak < an;) {
166 				c = tr[(*ak++)[i]];
167 				if (++count[c] == 1 && c != endch) {
168 					if (c < bmin)
169 						bmin = c;
170 					nc++;
171 				}
172 			}
173 			if (sp + nc > s + SIZE) {	/* Get more stack. */
174 				r_sort_a(a, n, i, tr, endch);
175 				continue;
176 			}
177 		}
178 
179 		/*
180 		 * Set top[]; push incompletely sorted bins onto stack.
181 		 * top[] = pointers to last out-of-place element in bins.
182 		 * count[] = counts of elements in bins.
183 		 * Before permuting: top[c-1] + count[c] = top[c];
184 		 * during deal: top[c] counts down to top[c-1].
185 		 */
186 		sp0 = sp1 = sp;		/* Stack position of biggest bin. */
187 		bigc = 2;		/* Size of biggest bin. */
188 		if (endch == 0)		/* Special case: set top[eos]. */
189 			top[0] = ak = a + count[0];
190 		else {
191 			ak = a;
192 			top[255] = an;
193 		}
194 		for (cp = count + bmin; nc > 0; cp++) {
195 			while (*cp == 0)	/* Find next non-empty pile. */
196 				cp++;
197 			if (*cp > 1) {
198 				if (*cp > bigc) {
199 					bigc = *cp;
200 					sp1 = sp;
201 				}
202 				push(ak, *cp, i+1);
203 			}
204 			top[cp-count] = ak += *cp;
205 			nc--;
206 		}
207 		swap(*sp0, *sp1, temp);	/* Play it safe -- biggest bin last. */
208 
209 		/*
210 		 * Permute misplacements home.  Already home: everything
211 		 * before aj, and in bin[c], items from top[c] on.
212 		 * Inner loop:
213 		 *	r = next element to put in place;
214 		 *	ak = top[r[i]] = location to put the next element.
215 		 *	aj = bottom of 1st disordered bin.
216 		 * Outer loop:
217 		 *	Once the 1st disordered bin is done, ie. aj >= ak,
218 		 *	aj<-aj + count[c] connects the bins in a linked list;
219 		 *	reset count[c].
220 		 */
221 		for (aj = a; aj < an;  *aj = r, aj += count[c], count[c] = 0)
222 			for (r = *aj;  aj < (ak = --top[c = tr[r[i]]]);)
223 				swap(*ak, r, t);
224 	}
225 }
226 
227 /* Stable sort, requiring additional memory. */
228 static void
229 r_sort_b(a, ta, n, i, tr, endch)
230 	const u_char **a, **ta;
231 	int n, i;
232 	const u_char *tr;
233 	u_int endch;
234 {
235 	static int count[256], nc, bmin;
236 	int c;
237 	const u_char **ak, **ai;
238 	stack s[512], *sp, *sp0, *sp1, temp;
239 	const u_char **top[256];
240 	int *cp, bigc;
241 
242 	sp = s;
243 	push(a, n, i);
244 	while (!empty(s)) {
245 		pop(a, n, i);
246 		if (n < THRESHOLD) {
247 			simplesort(a, n, i, tr, endch);
248 			continue;
249 		}
250 
251 		if (nc == 0) {
252 			bmin = 255;
253 			for (ak = a + n; --ak >= a;) {
254 				c = tr[(*ak)[i]];
255 				if (++count[c] == 1 && c != endch) {
256 					if (c < bmin)
257 						bmin = c;
258 					nc++;
259 				}
260 			}
261 			if (sp + nc > s + SIZE) {
262 				r_sort_b(a, ta, n, i, tr, endch);
263 				continue;
264 			}
265 		}
266 
267 		sp0 = sp1 = sp;
268 		bigc = 2;
269 		if (endch == 0) {
270 			top[0] = ak = a + count[0];
271 			count[0] = 0;
272 		} else {
273 			ak = a;
274 			top[255] = a + n;
275 			count[255] = 0;
276 		}
277 		for (cp = count + bmin; nc > 0; cp++) {
278 			while (*cp == 0)
279 				cp++;
280 			if ((c = *cp) > 1) {
281 				if (c > bigc) {
282 					bigc = c;
283 					sp1 = sp;
284 				}
285 				push(ak, c, i+1);
286 			}
287 			top[cp-count] = ak += c;
288 			*cp = 0;			/* Reset count[]. */
289 			nc--;
290 		}
291 		swap(*sp0, *sp1, temp);
292 
293 		for (ak = ta + n, ai = a+n; ak > ta;)	/* Copy to temp. */
294 			*--ak = *--ai;
295 		for (ak = ta+n; --ak >= ta;)		/* Deal to piles. */
296 			*--top[tr[(*ak)[i]]] = *ak;
297 	}
298 }
299 
300 static inline void
301 simplesort(a, n, b, tr, endch)	/* insertion sort */
302 	const u_char **a;
303 	int n, b;
304 	const u_char *tr;
305 	u_int endch;
306 {
307 	u_char ch;
308 	const u_char  **ak, **ai, *s, *t;
309 
310 	for (ak = a+1; --n >= 1; ak++)
311 		for (ai = ak; ai > a; ai--) {
312 			for (s = ai[0] + b, t = ai[-1] + b;
313 			    (ch = tr[*s]) != endch; s++, t++)
314 				if (ch != tr[*t])
315 					break;
316 			if (ch >= tr[*t])
317 				break;
318 			swap(ai[0], ai[-1], s);
319 		}
320 }
321