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