1 /*	$OpenBSD: merge.c,v 1.8 2005/08/08 08:05:37 espie 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 
54 static void setup(u_char *, u_char *, size_t, size_t,
55     int (*)(const void *, const void *));
56 static void insertionsort(u_char *, size_t, size_t,
57     int (*)(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  */
92 int
mergesort(void * base,size_t nmemb,size_t size,int (* cmp)(const void *,const void *))93 mergesort(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 	/*
107 	 * XXX
108 	 * Stupid subtraction for the Cray.
109 	 */
110 	iflag = 0;
111 	if (!(size % ISIZE) && !(((char *)base - (char *)0) % ISIZE))
112 		iflag = 1;
113 
114 	if ((list2 = malloc(nmemb * size + PSIZE)) == NULL)
115 		return (-1);
116 
117 	list1 = base;
118 	setup(list1, list2, nmemb, size, cmp);
119 	last = list2 + nmemb * size;
120 	i = big = 0;
121 	while (*EVAL(list2) != last) {
122 	    l2 = list1;
123 	    p1 = EVAL(list1);
124 	    for (tp2 = p2 = list2; p2 != last; p1 = EVAL(l2)) {
125 	    	p2 = *EVAL(p2);
126 	    	f1 = l2;
127 	    	f2 = l1 = list1 + (p2 - list2);
128 	    	if (p2 != last)
129 	    		p2 = *EVAL(p2);
130 	    	l2 = list1 + (p2 - list2);
131 	    	while (f1 < l1 && f2 < l2) {
132 	    		if ((*cmp)(f1, f2) <= 0) {
133 	    			q = f2;
134 	    			b = f1, t = l1;
135 	    			sense = -1;
136 	    		} else {
137 	    			q = f1;
138 	    			b = f2, t = l2;
139 	    			sense = 0;
140 	    		}
141 	    		if (!big) {	/* here i = 0 */
142 	    			while ((b += size) < t && cmp(q, b) >sense)
143 	    				if (++i == 6) {
144 	    					big = 1;
145 	    					goto EXPONENTIAL;
146 	    				}
147 	    		} else {
148 EXPONENTIAL:	    		for (i = size; ; i <<= 1)
149 	    				if ((p = (b + i)) >= t) {
150 	    					if ((p = t - size) > b &&
151 						    (*cmp)(q, p) <= sense)
152 	    						t = p;
153 	    					else
154 	    						b = p;
155 	    					break;
156 	    				} else if ((*cmp)(q, p) <= sense) {
157 	    					t = p;
158 	    					if ((size_t)i == size)
159 	    						big = 0;
160 	    					goto FASTCASE;
161 	    				} else
162 	    					b = p;
163 		    		while (t > b+size) {
164 	    				i = (((t - b) / size) >> 1) * size;
165 	    				if ((*cmp)(q, p = b + i) <= sense)
166 	    					t = p;
167 	    				else
168 	    					b = p;
169 	    			}
170 	    			goto COPY;
171 FASTCASE:	    		while ((size_t)i > size)
172 	    				if ((*cmp)(q,
173 	    					p = b + (i >>= 1)) <= sense)
174 	    					t = p;
175 	    				else
176 	    					b = p;
177 COPY:	    			b = t;
178 	    		}
179 	    		i = size;
180 	    		if (q == f1) {
181 	    			if (iflag) {
182 	    				ICOPY_LIST(f2, tp2, b);
183 	    				ICOPY_ELT(f1, tp2, i);
184 	    			} else {
185 	    				CCOPY_LIST(f2, tp2, b);
186 	    				CCOPY_ELT(f1, tp2, i);
187 	    			}
188 	    		} else {
189 	    			if (iflag) {
190 	    				ICOPY_LIST(f1, tp2, b);
191 	    				ICOPY_ELT(f2, tp2, i);
192 	    			} else {
193 	    				CCOPY_LIST(f1, tp2, b);
194 	    				CCOPY_ELT(f2, tp2, i);
195 	    			}
196 	    		}
197 	    	}
198 	    	if (f2 < l2) {
199 	    		if (iflag)
200 	    			ICOPY_LIST(f2, tp2, l2);
201 	    		else
202 	    			CCOPY_LIST(f2, tp2, l2);
203 	    	} else if (f1 < l1) {
204 	    		if (iflag)
205 	    			ICOPY_LIST(f1, tp2, l1);
206 	    		else
207 	    			CCOPY_LIST(f1, tp2, l1);
208 	    	}
209 	    	*p1 = l2;
210 	    }
211 	    tp2 = list1;	/* swap list1, list2 */
212 	    list1 = list2;
213 	    list2 = tp2;
214 	    last = list2 + nmemb*size;
215 	}
216 	if (base == list2) {
217 		memmove(list2, list1, nmemb*size);
218 		list2 = list1;
219 	}
220 	free(list2);
221 	return (0);
222 }
223 
224 #define	swap(a, b) {					\
225 		s = b;					\
226 		i = size;				\
227 		do {					\
228 			tmp = *a; *a++ = *s; *s++ = tmp; \
229 		} while (--i);				\
230 		a -= size;				\
231 	}
232 #define reverse(bot, top) {				\
233 	s = top;					\
234 	do {						\
235 		i = size;				\
236 		do {					\
237 			tmp = *bot; *bot++ = *s; *s++ = tmp; \
238 		} while (--i);				\
239 		s -= size2;				\
240 	} while(bot < s);				\
241 }
242 
243 /*
244  * Optional hybrid natural/pairwise first pass.  Eats up list1 in runs of
245  * increasing order, list2 in a corresponding linked list.  Checks for runs
246  * when THRESHOLD/2 pairs compare with same sense.  (Only used when NATURAL
247  * is defined.  Otherwise simple pairwise merging is used.)
248  */
249 void
setup(u_char * list1,u_char * list2,size_t n,size_t size,int (* cmp)(const void *,const void *))250 setup(u_char *list1, u_char *list2, size_t n, size_t size,
251     int (*cmp)(const void *, const void *))
252 {
253 	int i, length, size2, tmp, sense;
254 	u_char *f1, *f2, *s, *l2, *last, *p2;
255 
256 	size2 = size*2;
257 	if (n <= 5) {
258 		insertionsort(list1, n, size, cmp);
259 		*EVAL(list2) = (u_char*) list2 + n*size;
260 		return;
261 	}
262 	/*
263 	 * Avoid running pointers out of bounds; limit n to evens
264 	 * for simplicity.
265 	 */
266 	i = 4 + (n & 1);
267 	insertionsort(list1 + (n - i) * size, i, size, cmp);
268 	last = list1 + size * (n - i);
269 	*EVAL(list2 + (last - list1)) = list2 + n * size;
270 
271 #ifdef NATURAL
272 	p2 = list2;
273 	f1 = list1;
274 	sense = (cmp(f1, f1 + size) > 0);
275 	for (; f1 < last; sense = !sense) {
276 		length = 2;
277 					/* Find pairs with same sense. */
278 		for (f2 = f1 + size2; f2 < last; f2 += size2) {
279 			if ((cmp(f2, f2+ size) > 0) != sense)
280 				break;
281 			length += 2;
282 		}
283 		if (length < THRESHOLD) {		/* Pairwise merge */
284 			do {
285 				p2 = *EVAL(p2) = f1 + size2 - list1 + list2;
286 				if (sense > 0)
287 					swap (f1, f1 + size);
288 			} while ((f1 += size2) < f2);
289 		} else {				/* Natural merge */
290 			l2 = f2;
291 			for (f2 = f1 + size2; f2 < l2; f2 += size2) {
292 				if ((cmp(f2-size, f2) > 0) != sense) {
293 					p2 = *EVAL(p2) = f2 - list1 + list2;
294 					if (sense > 0)
295 						reverse(f1, f2-size);
296 					f1 = f2;
297 				}
298 			}
299 			if (sense > 0)
300 				reverse (f1, f2-size);
301 			f1 = f2;
302 			if (f2 < last || cmp(f2 - size, f2) > 0)
303 				p2 = *EVAL(p2) = f2 - list1 + list2;
304 			else
305 				p2 = *EVAL(p2) = list2 + n*size;
306 		}
307 	}
308 #else		/* pairwise merge only. */
309 	for (f1 = list1, p2 = list2; f1 < last; f1 += size2) {
310 		p2 = *EVAL(p2) = p2 + size2;
311 		if (cmp (f1, f1 + size) > 0)
312 			swap(f1, f1 + size);
313 	}
314 #endif /* NATURAL */
315 }
316 
317 /*
318  * This is to avoid out-of-bounds addresses in sorting the
319  * last 4 elements.
320  */
321 static void
insertionsort(u_char * a,size_t n,size_t size,int (* cmp)(const void *,const void *))322 insertionsort(u_char *a, size_t n, size_t size,
323     int (*cmp)(const void *, const void *))
324 {
325 	u_char *ai, *s, *t, *u, tmp;
326 	int i;
327 
328 	for (ai = a+size; --n >= 1; ai += size)
329 		for (t = ai; t > a; t -= size) {
330 			u = t - size;
331 			if (cmp(u, t) <= 0)
332 				break;
333 			swap(u, t);
334 		}
335 }
336