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