11573Srgrimes/*-
21573Srgrimes * Copyright (c) 1992, 1993
31573Srgrimes *	The Regents of the University of California.  All rights reserved.
41573Srgrimes *
51573Srgrimes * This code is derived from software contributed to Berkeley by
61573Srgrimes * Peter McIlroy.
71573Srgrimes *
81573Srgrimes * Redistribution and use in source and binary forms, with or without
91573Srgrimes * modification, are permitted provided that the following conditions
101573Srgrimes * are met:
111573Srgrimes * 1. Redistributions of source code must retain the above copyright
121573Srgrimes *    notice, this list of conditions and the following disclaimer.
131573Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
141573Srgrimes *    notice, this list of conditions and the following disclaimer in the
151573Srgrimes *    documentation and/or other materials provided with the distribution.
16251672Semaste * 3. Neither the name of the University nor the names of its contributors
171573Srgrimes *    may be used to endorse or promote products derived from this software
181573Srgrimes *    without specific prior written permission.
191573Srgrimes *
201573Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
211573Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
221573Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
231573Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
241573Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
251573Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
261573Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
271573Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
281573Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
291573Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
301573Srgrimes * SUCH DAMAGE.
311573Srgrimes */
321573Srgrimes
331573Srgrimes#if defined(LIBC_SCCS) && !defined(lint)
341573Srgrimesstatic char sccsid[] = "@(#)merge.c	8.2 (Berkeley) 2/14/94";
351573Srgrimes#endif /* LIBC_SCCS and not lint */
3692889Sobrien#include <sys/cdefs.h>
3792889Sobrien__FBSDID("$FreeBSD$");
381573Srgrimes
391573Srgrimes/*
401573Srgrimes * Hybrid exponential search/linear search merge sort with hybrid
411573Srgrimes * natural/pairwise first pass.  Requires about .3% more comparisons
421573Srgrimes * for random data than LSMS with pairwise first pass alone.
431573Srgrimes * It works for objects as small as two bytes.
441573Srgrimes */
451573Srgrimes
461573Srgrimes#define NATURAL
471573Srgrimes#define THRESHOLD 16	/* Best choice for natural merge cut-off. */
481573Srgrimes
491573Srgrimes/* #define NATURAL to get hybrid natural merge.
501573Srgrimes * (The default is pairwise merging.)
511573Srgrimes */
521573Srgrimes
531573Srgrimes#include <sys/types.h>
541573Srgrimes
551573Srgrimes#include <errno.h>
561573Srgrimes#include <stdlib.h>
571573Srgrimes#include <string.h>
581573Srgrimes
59140098Sbrianstatic void setup(u_char *, u_char *, size_t, size_t,
60140098Sbrian    int (*)(const void *, const void *));
61140098Sbrianstatic void insertionsort(u_char *, size_t, size_t,
62140098Sbrian    int (*)(const void *, const void *));
631573Srgrimes
641573Srgrimes#define ISIZE sizeof(int)
651573Srgrimes#define PSIZE sizeof(u_char *)
661573Srgrimes#define ICOPY_LIST(src, dst, last)				\
671573Srgrimes	do							\
681573Srgrimes	*(int*)dst = *(int*)src, src += ISIZE, dst += ISIZE;	\
691573Srgrimes	while(src < last)
701573Srgrimes#define ICOPY_ELT(src, dst, i)					\
711573Srgrimes	do							\
721573Srgrimes	*(int*) dst = *(int*) src, src += ISIZE, dst += ISIZE;	\
731573Srgrimes	while (i -= ISIZE)
741573Srgrimes
751573Srgrimes#define CCOPY_LIST(src, dst, last)		\
761573Srgrimes	do					\
771573Srgrimes		*dst++ = *src++;		\
781573Srgrimes	while (src < last)
791573Srgrimes#define CCOPY_ELT(src, dst, i)			\
801573Srgrimes	do					\
811573Srgrimes		*dst++ = *src++;		\
821573Srgrimes	while (i -= 1)
838870Srgrimes
841573Srgrimes/*
851573Srgrimes * Find the next possible pointer head.  (Trickery for forcing an array
861573Srgrimes * to do double duty as a linked list when objects do not align with word
871573Srgrimes * boundaries.
881573Srgrimes */
891573Srgrimes/* Assumption: PSIZE is a power of 2. */
901573Srgrimes#define EVAL(p) (u_char **)						\
911573Srgrimes	((u_char *)0 +							\
921573Srgrimes	    (((u_char *)p + PSIZE - 1 - (u_char *) 0) & ~(PSIZE - 1)))
931573Srgrimes
941573Srgrimes/*
951573Srgrimes * Arguments are as for qsort.
961573Srgrimes */
971573Srgrimesint
981573Srgrimesmergesort(base, nmemb, size, cmp)
991573Srgrimes	void *base;
1001573Srgrimes	size_t nmemb;
10192889Sobrien	size_t size;
10292905Sobrien	int (*cmp)(const void *, const void *);
1031573Srgrimes{
104140098Sbrian	size_t i;
105140098Sbrian	int sense;
1061573Srgrimes	int big, iflag;
10792889Sobrien	u_char *f1, *f2, *t, *b, *tp2, *q, *l1, *l2;
1081573Srgrimes	u_char *list2, *list1, *p2, *p, *last, **p1;
1091573Srgrimes
1101573Srgrimes	if (size < PSIZE / 2) {		/* Pointers must fit into 2 * size. */
1111573Srgrimes		errno = EINVAL;
1121573Srgrimes		return (-1);
1131573Srgrimes	}
1141573Srgrimes
11540896Srnordier	if (nmemb == 0)
11640896Srnordier		return (0);
11740896Srnordier
1181573Srgrimes	/*
1191573Srgrimes	 * XXX
1201573Srgrimes	 * Stupid subtraction for the Cray.
1211573Srgrimes	 */
1221573Srgrimes	iflag = 0;
1231573Srgrimes	if (!(size % ISIZE) && !(((char *)base - (char *)0) % ISIZE))
1241573Srgrimes		iflag = 1;
1251573Srgrimes
1261573Srgrimes	if ((list2 = malloc(nmemb * size + PSIZE)) == NULL)
1271573Srgrimes		return (-1);
1281573Srgrimes
1291573Srgrimes	list1 = base;
1301573Srgrimes	setup(list1, list2, nmemb, size, cmp);
1311573Srgrimes	last = list2 + nmemb * size;
1321573Srgrimes	i = big = 0;
1331573Srgrimes	while (*EVAL(list2) != last) {
1341573Srgrimes	    l2 = list1;
1351573Srgrimes	    p1 = EVAL(list1);
1361573Srgrimes	    for (tp2 = p2 = list2; p2 != last; p1 = EVAL(l2)) {
1371573Srgrimes	    	p2 = *EVAL(p2);
1381573Srgrimes	    	f1 = l2;
1391573Srgrimes	    	f2 = l1 = list1 + (p2 - list2);
1401573Srgrimes	    	if (p2 != last)
1411573Srgrimes	    		p2 = *EVAL(p2);
1421573Srgrimes	    	l2 = list1 + (p2 - list2);
1431573Srgrimes	    	while (f1 < l1 && f2 < l2) {
1441573Srgrimes	    		if ((*cmp)(f1, f2) <= 0) {
1451573Srgrimes	    			q = f2;
1461573Srgrimes	    			b = f1, t = l1;
1471573Srgrimes	    			sense = -1;
1481573Srgrimes	    		} else {
1491573Srgrimes	    			q = f1;
1501573Srgrimes	    			b = f2, t = l2;
1511573Srgrimes	    			sense = 0;
1521573Srgrimes	    		}
1531573Srgrimes	    		if (!big) {	/* here i = 0 */
15440900Srnordier				while ((b += size) < t && cmp(q, b) >sense)
1551573Srgrimes	    				if (++i == 6) {
1561573Srgrimes	    					big = 1;
1571573Srgrimes	    					goto EXPONENTIAL;
1581573Srgrimes	    				}
1591573Srgrimes	    		} else {
1601573SrgrimesEXPONENTIAL:	    		for (i = size; ; i <<= 1)
1611573Srgrimes	    				if ((p = (b + i)) >= t) {
1621573Srgrimes	    					if ((p = t - size) > b &&
1631573Srgrimes						    (*cmp)(q, p) <= sense)
1641573Srgrimes	    						t = p;
1651573Srgrimes	    					else
1661573Srgrimes	    						b = p;
1671573Srgrimes	    					break;
1681573Srgrimes	    				} else if ((*cmp)(q, p) <= sense) {
1691573Srgrimes	    					t = p;
1701573Srgrimes	    					if (i == size)
1718870Srgrimes	    						big = 0;
1721573Srgrimes	    					goto FASTCASE;
1731573Srgrimes	    				} else
1741573Srgrimes	    					b = p;
17540900Srnordier				while (t > b+size) {
1761573Srgrimes	    				i = (((t - b) / size) >> 1) * size;
1771573Srgrimes	    				if ((*cmp)(q, p = b + i) <= sense)
1781573Srgrimes	    					t = p;
1791573Srgrimes	    				else
1801573Srgrimes	    					b = p;
1811573Srgrimes	    			}
1821573Srgrimes	    			goto COPY;
1831573SrgrimesFASTCASE:	    		while (i > size)
1841573Srgrimes	    				if ((*cmp)(q,
1851573Srgrimes	    					p = b + (i >>= 1)) <= sense)
1861573Srgrimes	    					t = p;
1871573Srgrimes	    				else
1881573Srgrimes	    					b = p;
1891573SrgrimesCOPY:	    			b = t;
1901573Srgrimes	    		}
1911573Srgrimes	    		i = size;
1921573Srgrimes	    		if (q == f1) {
1931573Srgrimes	    			if (iflag) {
1941573Srgrimes	    				ICOPY_LIST(f2, tp2, b);
1951573Srgrimes	    				ICOPY_ELT(f1, tp2, i);
1961573Srgrimes	    			} else {
1971573Srgrimes	    				CCOPY_LIST(f2, tp2, b);
1981573Srgrimes	    				CCOPY_ELT(f1, tp2, i);
1991573Srgrimes	    			}
2001573Srgrimes	    		} else {
2011573Srgrimes	    			if (iflag) {
2021573Srgrimes	    				ICOPY_LIST(f1, tp2, b);
2031573Srgrimes	    				ICOPY_ELT(f2, tp2, i);
2041573Srgrimes	    			} else {
2051573Srgrimes	    				CCOPY_LIST(f1, tp2, b);
2061573Srgrimes	    				CCOPY_ELT(f2, tp2, i);
2071573Srgrimes	    			}
2081573Srgrimes	    		}
2091573Srgrimes	    	}
2101573Srgrimes	    	if (f2 < l2) {
2111573Srgrimes	    		if (iflag)
2121573Srgrimes	    			ICOPY_LIST(f2, tp2, l2);
2131573Srgrimes	    		else
2141573Srgrimes	    			CCOPY_LIST(f2, tp2, l2);
2151573Srgrimes	    	} else if (f1 < l1) {
2161573Srgrimes	    		if (iflag)
2171573Srgrimes	    			ICOPY_LIST(f1, tp2, l1);
2181573Srgrimes	    		else
2191573Srgrimes	    			CCOPY_LIST(f1, tp2, l1);
2201573Srgrimes	    	}
2211573Srgrimes	    	*p1 = l2;
2221573Srgrimes	    }
2231573Srgrimes	    tp2 = list1;	/* swap list1, list2 */
2241573Srgrimes	    list1 = list2;
2251573Srgrimes	    list2 = tp2;
2261573Srgrimes	    last = list2 + nmemb*size;
2271573Srgrimes	}
2281573Srgrimes	if (base == list2) {
2291573Srgrimes		memmove(list2, list1, nmemb*size);
2301573Srgrimes		list2 = list1;
2311573Srgrimes	}
2321573Srgrimes	free(list2);
2331573Srgrimes	return (0);
2341573Srgrimes}
2351573Srgrimes
2361573Srgrimes#define	swap(a, b) {					\
2371573Srgrimes		s = b;					\
2381573Srgrimes		i = size;				\
2391573Srgrimes		do {					\
2401573Srgrimes			tmp = *a; *a++ = *s; *s++ = tmp; \
2411573Srgrimes		} while (--i);				\
2421573Srgrimes		a -= size;				\
2431573Srgrimes	}
2441573Srgrimes#define reverse(bot, top) {				\
2451573Srgrimes	s = top;					\
2461573Srgrimes	do {						\
2471573Srgrimes		i = size;				\
2481573Srgrimes		do {					\
2491573Srgrimes			tmp = *bot; *bot++ = *s; *s++ = tmp; \
2501573Srgrimes		} while (--i);				\
2511573Srgrimes		s -= size2;				\
2521573Srgrimes	} while(bot < s);				\
2531573Srgrimes}
2541573Srgrimes
2551573Srgrimes/*
2561573Srgrimes * Optional hybrid natural/pairwise first pass.  Eats up list1 in runs of
2571573Srgrimes * increasing order, list2 in a corresponding linked list.  Checks for runs
2581573Srgrimes * when THRESHOLD/2 pairs compare with same sense.  (Only used when NATURAL
2591573Srgrimes * is defined.  Otherwise simple pairwise merging is used.)
2601573Srgrimes */
2611573Srgrimesvoid
2621573Srgrimessetup(list1, list2, n, size, cmp)
2631573Srgrimes	size_t n, size;
26492905Sobrien	int (*cmp)(const void *, const void *);
2651573Srgrimes	u_char *list1, *list2;
2661573Srgrimes{
2671573Srgrimes	int i, length, size2, tmp, sense;
2681573Srgrimes	u_char *f1, *f2, *s, *l2, *last, *p2;
2691573Srgrimes
2701573Srgrimes	size2 = size*2;
2711573Srgrimes	if (n <= 5) {
2721573Srgrimes		insertionsort(list1, n, size, cmp);
2731573Srgrimes		*EVAL(list2) = (u_char*) list2 + n*size;
2741573Srgrimes		return;
2751573Srgrimes	}
2761573Srgrimes	/*
2771573Srgrimes	 * Avoid running pointers out of bounds; limit n to evens
2781573Srgrimes	 * for simplicity.
2791573Srgrimes	 */
2801573Srgrimes	i = 4 + (n & 1);
2811573Srgrimes	insertionsort(list1 + (n - i) * size, i, size, cmp);
2821573Srgrimes	last = list1 + size * (n - i);
2831573Srgrimes	*EVAL(list2 + (last - list1)) = list2 + n * size;
2841573Srgrimes
2851573Srgrimes#ifdef NATURAL
2861573Srgrimes	p2 = list2;
2871573Srgrimes	f1 = list1;
2881573Srgrimes	sense = (cmp(f1, f1 + size) > 0);
2891573Srgrimes	for (; f1 < last; sense = !sense) {
2901573Srgrimes		length = 2;
2911573Srgrimes					/* Find pairs with same sense. */
2921573Srgrimes		for (f2 = f1 + size2; f2 < last; f2 += size2) {
2931573Srgrimes			if ((cmp(f2, f2+ size) > 0) != sense)
2941573Srgrimes				break;
2951573Srgrimes			length += 2;
2961573Srgrimes		}
2971573Srgrimes		if (length < THRESHOLD) {		/* Pairwise merge */
2981573Srgrimes			do {
2991573Srgrimes				p2 = *EVAL(p2) = f1 + size2 - list1 + list2;
3001573Srgrimes				if (sense > 0)
3011573Srgrimes					swap (f1, f1 + size);
3021573Srgrimes			} while ((f1 += size2) < f2);
3031573Srgrimes		} else {				/* Natural merge */
3041573Srgrimes			l2 = f2;
3051573Srgrimes			for (f2 = f1 + size2; f2 < l2; f2 += size2) {
3061573Srgrimes				if ((cmp(f2-size, f2) > 0) != sense) {
3071573Srgrimes					p2 = *EVAL(p2) = f2 - list1 + list2;
3081573Srgrimes					if (sense > 0)
3091573Srgrimes						reverse(f1, f2-size);
3101573Srgrimes					f1 = f2;
3111573Srgrimes				}
3121573Srgrimes			}
3131573Srgrimes			if (sense > 0)
3141573Srgrimes				reverse (f1, f2-size);
3151573Srgrimes			f1 = f2;
3161573Srgrimes			if (f2 < last || cmp(f2 - size, f2) > 0)
3171573Srgrimes				p2 = *EVAL(p2) = f2 - list1 + list2;
3181573Srgrimes			else
3191573Srgrimes				p2 = *EVAL(p2) = list2 + n*size;
3201573Srgrimes		}
3211573Srgrimes	}
3221573Srgrimes#else		/* pairwise merge only. */
3231573Srgrimes	for (f1 = list1, p2 = list2; f1 < last; f1 += size2) {
3241573Srgrimes		p2 = *EVAL(p2) = p2 + size2;
3251573Srgrimes		if (cmp (f1, f1 + size) > 0)
3261573Srgrimes			swap(f1, f1 + size);
3271573Srgrimes	}
3281573Srgrimes#endif /* NATURAL */
3291573Srgrimes}
3301573Srgrimes
3311573Srgrimes/*
3321573Srgrimes * This is to avoid out-of-bounds addresses in sorting the
3331573Srgrimes * last 4 elements.
3341573Srgrimes */
3351573Srgrimesstatic void
3361573Srgrimesinsertionsort(a, n, size, cmp)
3371573Srgrimes	u_char *a;
3381573Srgrimes	size_t n, size;
33992905Sobrien	int (*cmp)(const void *, const void *);
3401573Srgrimes{
3411573Srgrimes	u_char *ai, *s, *t, *u, tmp;
3421573Srgrimes	int i;
3431573Srgrimes
3441573Srgrimes	for (ai = a+size; --n >= 1; ai += size)
3451573Srgrimes		for (t = ai; t > a; t -= size) {
3461573Srgrimes			u = t - size;
3471573Srgrimes			if (cmp(u, t) <= 0)
3481573Srgrimes				break;
3491573Srgrimes			swap(u, t);
3501573Srgrimes		}
3511573Srgrimes}
352