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