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