1/*	$OpenBSD: merge.c,v 1.10 2015/06/21 03:20:56 millert Exp $ */
2/*-
3 * Copyright (c) 1992, 1993
4 *	The Regents of the University of California.  All rights reserved.
5 *
6 * This code is derived from software contributed to Berkeley by
7 * Peter McIlroy.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in the
16 *    documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34/*
35 * Hybrid exponential search/linear search merge sort with hybrid
36 * natural/pairwise first pass.  Requires about .3% more comparisons
37 * for random data than LSMS with pairwise first pass alone.
38 * It works for objects as small as two bytes.
39 */
40
41#define NATURAL
42#define THRESHOLD 16	/* Best choice for natural merge cut-off. */
43
44/* #define NATURAL to get hybrid natural merge.
45 * (The default is pairwise merging.)
46 */
47
48#include <sys/types.h>
49
50#include <errno.h>
51#include <stdlib.h>
52#include <string.h>
53
54static void setup(u_char *list1, u_char *list2, size_t n, size_t size,
55    int (*cmp)(const void *, const void *));
56static void insertionsort(u_char *a, size_t n, size_t size,
57    int (*cmp)(const void *, const void *));
58
59#define ISIZE sizeof(int)
60#define PSIZE sizeof(u_char *)
61#define ICOPY_LIST(src, dst, last)				\
62	do							\
63	*(int*)dst = *(int*)src, src += ISIZE, dst += ISIZE;	\
64	while(src < last)
65#define ICOPY_ELT(src, dst, i)					\
66	do							\
67	*(int*) dst = *(int*) src, src += ISIZE, dst += ISIZE;	\
68	while (i -= ISIZE)
69
70#define CCOPY_LIST(src, dst, last)		\
71	do					\
72		*dst++ = *src++;		\
73	while (src < last)
74#define CCOPY_ELT(src, dst, i)			\
75	do					\
76		*dst++ = *src++;		\
77	while (i -= 1)
78
79/*
80 * Find the next possible pointer head.  (Trickery for forcing an array
81 * to do double duty as a linked list when objects do not align with word
82 * boundaries.
83 */
84/* Assumption: PSIZE is a power of 2. */
85#define EVAL(p) (u_char **)						\
86	((u_char *)0 +							\
87	    (((u_char *)p + PSIZE - 1 - (u_char *) 0) & ~(PSIZE - 1)))
88
89/*
90 * Arguments are as for qsort.
91 */
92int
93mergesort(void *base, size_t nmemb, size_t size,
94    int (*cmp)(const void *, const void *))
95{
96	int i, sense;
97	int big, iflag;
98	u_char *f1, *f2, *t, *b, *tp2, *q, *l1, *l2;
99	u_char *list2, *list1, *p2, *p, *last, **p1;
100
101	if (size < PSIZE / 2) {		/* Pointers must fit into 2 * size. */
102		errno = EINVAL;
103		return (-1);
104	}
105
106	if (nmemb == 0)
107		return (0);
108
109	/*
110	 * XXX
111	 * Stupid subtraction for the Cray.
112	 */
113	iflag = 0;
114	if (!(size % ISIZE) && !(((char *)base - (char *)0) % ISIZE))
115		iflag = 1;
116
117	if ((list2 = malloc(nmemb * size + PSIZE)) == NULL)
118		return (-1);
119
120	list1 = base;
121	setup(list1, list2, nmemb, size, cmp);
122	last = list2 + nmemb * size;
123	i = big = 0;
124	while (*EVAL(list2) != last) {
125	    l2 = list1;
126	    p1 = EVAL(list1);
127	    for (tp2 = p2 = list2; p2 != last; p1 = EVAL(l2)) {
128	    	p2 = *EVAL(p2);
129	    	f1 = l2;
130	    	f2 = l1 = list1 + (p2 - list2);
131	    	if (p2 != last)
132	    		p2 = *EVAL(p2);
133	    	l2 = list1 + (p2 - list2);
134	    	while (f1 < l1 && f2 < l2) {
135	    		if ((*cmp)(f1, f2) <= 0) {
136	    			q = f2;
137	    			b = f1, t = l1;
138	    			sense = -1;
139	    		} else {
140	    			q = f1;
141	    			b = f2, t = l2;
142	    			sense = 0;
143	    		}
144	    		if (!big) {	/* here i = 0 */
145	    			while ((b += size) < t && cmp(q, b) >sense)
146	    				if (++i == 6) {
147	    					big = 1;
148	    					goto EXPONENTIAL;
149	    				}
150	    		} else {
151EXPONENTIAL:	    		for (i = size; ; i <<= 1)
152	    				if ((p = (b + i)) >= t) {
153	    					if ((p = t - size) > b &&
154						    (*cmp)(q, p) <= sense)
155	    						t = p;
156	    					else
157	    						b = p;
158	    					break;
159	    				} else if ((*cmp)(q, p) <= sense) {
160	    					t = p;
161	    					if (i == size)
162	    						big = 0;
163	    					goto FASTCASE;
164	    				} else
165	    					b = p;
166		    		while (t > b+size) {
167	    				i = (((t - b) / size) >> 1) * size;
168	    				if ((*cmp)(q, p = b + i) <= sense)
169	    					t = p;
170	    				else
171	    					b = p;
172	    			}
173	    			goto COPY;
174FASTCASE:	    		while (i > size)
175	    				if ((*cmp)(q,
176	    					p = b + (i >>= 1)) <= sense)
177	    					t = p;
178	    				else
179	    					b = p;
180COPY:	    			b = t;
181	    		}
182	    		i = size;
183	    		if (q == f1) {
184	    			if (iflag) {
185	    				ICOPY_LIST(f2, tp2, b);
186	    				ICOPY_ELT(f1, tp2, i);
187	    			} else {
188	    				CCOPY_LIST(f2, tp2, b);
189	    				CCOPY_ELT(f1, tp2, i);
190	    			}
191	    		} else {
192	    			if (iflag) {
193	    				ICOPY_LIST(f1, tp2, b);
194	    				ICOPY_ELT(f2, tp2, i);
195	    			} else {
196	    				CCOPY_LIST(f1, tp2, b);
197	    				CCOPY_ELT(f2, tp2, i);
198	    			}
199	    		}
200	    	}
201	    	if (f2 < l2) {
202	    		if (iflag)
203	    			ICOPY_LIST(f2, tp2, l2);
204	    		else
205	    			CCOPY_LIST(f2, tp2, l2);
206	    	} else if (f1 < l1) {
207	    		if (iflag)
208	    			ICOPY_LIST(f1, tp2, l1);
209	    		else
210	    			CCOPY_LIST(f1, tp2, l1);
211	    	}
212	    	*p1 = l2;
213	    }
214	    tp2 = list1;	/* swap list1, list2 */
215	    list1 = list2;
216	    list2 = tp2;
217	    last = list2 + nmemb*size;
218	}
219	if (base == list2) {
220		memmove(list2, list1, nmemb*size);
221		list2 = list1;
222	}
223	free(list2);
224	return (0);
225}
226
227#define	swap(a, b) {					\
228		s = b;					\
229		i = size;				\
230		do {					\
231			tmp = *a; *a++ = *s; *s++ = tmp; \
232		} while (--i);				\
233		a -= size;				\
234	}
235#define reverse(bot, top) {				\
236	s = top;					\
237	do {						\
238		i = size;				\
239		do {					\
240			tmp = *bot; *bot++ = *s; *s++ = tmp; \
241		} while (--i);				\
242		s -= size2;				\
243	} while(bot < s);				\
244}
245
246/*
247 * Optional hybrid natural/pairwise first pass.  Eats up list1 in runs of
248 * increasing order, list2 in a corresponding linked list.  Checks for runs
249 * when THRESHOLD/2 pairs compare with same sense.  (Only used when NATURAL
250 * is defined.  Otherwise simple pairwise merging is used.)
251 */
252void
253setup(u_char *list1, u_char *list2, size_t n, size_t size,
254    int (*cmp)(const void *, const void *))
255{
256	int i, length, size2, sense;
257	u_char tmp, *f1, *f2, *s, *l2, *last, *p2;
258
259	size2 = size*2;
260	if (n <= 5) {
261		insertionsort(list1, n, size, cmp);
262		*EVAL(list2) = (u_char*) list2 + n*size;
263		return;
264	}
265	/*
266	 * Avoid running pointers out of bounds; limit n to evens
267	 * for simplicity.
268	 */
269	i = 4 + (n & 1);
270	insertionsort(list1 + (n - i) * size, i, size, cmp);
271	last = list1 + size * (n - i);
272	*EVAL(list2 + (last - list1)) = list2 + n * size;
273
274#ifdef NATURAL
275	p2 = list2;
276	f1 = list1;
277	sense = (cmp(f1, f1 + size) > 0);
278	for (; f1 < last; sense = !sense) {
279		length = 2;
280					/* Find pairs with same sense. */
281		for (f2 = f1 + size2; f2 < last; f2 += size2) {
282			if ((cmp(f2, f2+ size) > 0) != sense)
283				break;
284			length += 2;
285		}
286		if (length < THRESHOLD) {		/* Pairwise merge */
287			do {
288				p2 = *EVAL(p2) = f1 + size2 - list1 + list2;
289				if (sense > 0)
290					swap (f1, f1 + size);
291			} while ((f1 += size2) < f2);
292		} else {				/* Natural merge */
293			l2 = f2;
294			for (f2 = f1 + size2; f2 < l2; f2 += size2) {
295				if ((cmp(f2-size, f2) > 0) != sense) {
296					p2 = *EVAL(p2) = f2 - list1 + list2;
297					if (sense > 0)
298						reverse(f1, f2-size);
299					f1 = f2;
300				}
301			}
302			if (sense > 0)
303				reverse (f1, f2-size);
304			f1 = f2;
305			if (f2 < last || cmp(f2 - size, f2) > 0)
306				p2 = *EVAL(p2) = f2 - list1 + list2;
307			else
308				p2 = *EVAL(p2) = list2 + n*size;
309		}
310	}
311#else		/* pairwise merge only. */
312	for (f1 = list1, p2 = list2; f1 < last; f1 += size2) {
313		p2 = *EVAL(p2) = p2 + size2;
314		if (cmp (f1, f1 + size) > 0)
315			swap(f1, f1 + size);
316	}
317#endif /* NATURAL */
318}
319
320/*
321 * This is to avoid out-of-bounds addresses in sorting the
322 * last 4 elements.
323 */
324static void
325insertionsort(u_char *a, size_t n, size_t size,
326    int (*cmp)(const void *, const void *))
327{
328	u_char *ai, *s, *t, *u, tmp;
329	int i;
330
331	for (ai = a+size; --n >= 1; ai += size)
332		for (t = ai; t > a; t -= size) {
333			u = t - size;
334			if (cmp(u, t) <= 0)
335				break;
336			swap(u, t);
337		}
338}
339