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