xref: /netbsd-src/lib/libc/stdlib/merge.c (revision 2a399c6883d870daece976daec6ffa7bb7f934ce)
1 /*	$NetBSD: merge.c,v 1.5 1997/07/21 14:08:56 jtc Exp $	*/
2 
3 /*-
4  * Copyright (c) 1992, 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.
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 #include <sys/cdefs.h>
40 #if defined(LIBC_SCCS) && !defined(lint)
41 #if 0
42 static char sccsid[] = "from: @(#)merge.c	8.2 (Berkeley) 2/14/94";
43 #else
44 __RCSID("$NetBSD: merge.c,v 1.5 1997/07/21 14:08:56 jtc Exp $");
45 #endif
46 #endif /* LIBC_SCCS and not lint */
47 
48 /*
49  * Hybrid exponential search/linear search merge sort with hybrid
50  * natural/pairwise first pass.  Requires about .3% more comparisons
51  * for random data than LSMS with pairwise first pass alone.
52  * It works for objects as small as two bytes.
53  */
54 
55 #define NATURAL
56 #define THRESHOLD 16	/* Best choice for natural merge cut-off. */
57 
58 /* #define NATURAL to get hybrid natural merge.
59  * (The default is pairwise merging.)
60  */
61 
62 #include "namespace.h"
63 #include <sys/types.h>
64 
65 #include <errno.h>
66 #include <stdlib.h>
67 #include <string.h>
68 
69 #ifdef __weak_alias
70 __weak_alias(mergesort,_mergesort);
71 #endif
72 
73 static void setup __P((u_char *, u_char *, size_t, size_t,
74     int (*)(const void *, const void *)));
75 static void insertionsort __P((u_char *, size_t, size_t,
76     int (*)(const void *, const void *)));
77 
78 #define ISIZE sizeof(int)
79 #define PSIZE sizeof(u_char *)
80 #define ICOPY_LIST(src, dst, last)				\
81 	do							\
82 	*(int*)dst = *(int*)src, src += ISIZE, dst += ISIZE;	\
83 	while(src < last)
84 #define ICOPY_ELT(src, dst, i)					\
85 	do							\
86 	*(int*) dst = *(int*) src, src += ISIZE, dst += ISIZE;	\
87 	while (i -= ISIZE)
88 
89 #define CCOPY_LIST(src, dst, last)		\
90 	do					\
91 		*dst++ = *src++;		\
92 	while (src < last)
93 #define CCOPY_ELT(src, dst, i)			\
94 	do					\
95 		*dst++ = *src++;		\
96 	while (i -= 1)
97 
98 /*
99  * Find the next possible pointer head.  (Trickery for forcing an array
100  * to do double duty as a linked list when objects do not align with word
101  * boundaries.
102  */
103 /* Assumption: PSIZE is a power of 2. */
104 #define EVAL(p) (u_char **)						\
105 	((u_char *)0 +							\
106 	    (((u_char *)p + PSIZE - 1 - (u_char *) 0) & ~(PSIZE - 1)))
107 
108 /*
109  * Arguments are as for qsort.
110  */
111 int
112 mergesort(base, nmemb, size, cmp)
113 	void *base;
114 	size_t nmemb;
115 	register size_t size;
116 	int (*cmp) __P((const void *, const void *));
117 {
118 	register int i, sense;
119 	int big, iflag;
120 	register u_char *f1, *f2, *t, *b, *tp2, *q, *l1, *l2;
121 	u_char *list2, *list1, *p2, *p, *last, **p1;
122 
123 	if (size < PSIZE / 2) {		/* Pointers must fit into 2 * size. */
124 		errno = EINVAL;
125 		return (-1);
126 	}
127 
128 	/*
129 	 * XXX
130 	 * Stupid subtraction for the Cray.
131 	 */
132 	iflag = 0;
133 	if (!(size % ISIZE) && !(((char *)base - (char *)0) % ISIZE))
134 		iflag = 1;
135 
136 	if ((list2 = malloc(nmemb * size + PSIZE)) == NULL)
137 		return (-1);
138 
139 	list1 = base;
140 	setup(list1, list2, nmemb, size, cmp);
141 	last = list2 + nmemb * size;
142 	i = big = 0;
143 	while (*EVAL(list2) != last) {
144 	    l2 = list1;
145 	    p1 = EVAL(list1);
146 	    for (tp2 = p2 = list2; p2 != last; p1 = EVAL(l2)) {
147 	    	p2 = *EVAL(p2);
148 	    	f1 = l2;
149 	    	f2 = l1 = list1 + (p2 - list2);
150 	    	if (p2 != last)
151 	    		p2 = *EVAL(p2);
152 	    	l2 = list1 + (p2 - list2);
153 	    	while (f1 < l1 && f2 < l2) {
154 	    		if ((*cmp)(f1, f2) <= 0) {
155 	    			q = f2;
156 	    			b = f1, t = l1;
157 	    			sense = -1;
158 	    		} else {
159 	    			q = f1;
160 	    			b = f2, t = l2;
161 	    			sense = 0;
162 	    		}
163 	    		if (!big) {	/* here i = 0 */
164 #if 0
165 LINEAR:
166 #endif
167 				while ((b += size) < t && cmp(q, b) >sense)
168 	    				if (++i == 6) {
169 	    					big = 1;
170 	    					goto EXPONENTIAL;
171 	    				}
172 	    		} else {
173 EXPONENTIAL:	    		for (i = size; ; i <<= 1)
174 	    				if ((p = (b + i)) >= t) {
175 	    					if ((p = t - size) > b &&
176 						    (*cmp)(q, p) <= sense)
177 	    						t = p;
178 	    					else
179 	    						b = p;
180 	    					break;
181 	    				} else if ((*cmp)(q, p) <= sense) {
182 	    					t = p;
183 	    					if (i == size)
184 	    						big = 0;
185 	    					goto FASTCASE;
186 	    				} else
187 	    					b = p;
188 #if 0
189 SLOWCASE:
190 #endif
191 				while (t > b+size) {
192 	    				i = (((t - b) / size) >> 1) * size;
193 	    				if ((*cmp)(q, p = b + i) <= sense)
194 	    					t = p;
195 	    				else
196 	    					b = p;
197 	    			}
198 	    			goto COPY;
199 FASTCASE:	    		while (i > size)
200 	    				if ((*cmp)(q,
201 	    					p = b + (i >>= 1)) <= sense)
202 	    					t = p;
203 	    				else
204 	    					b = p;
205 COPY:	    			b = t;
206 	    		}
207 	    		i = size;
208 	    		if (q == f1) {
209 	    			if (iflag) {
210 	    				ICOPY_LIST(f2, tp2, b);
211 	    				ICOPY_ELT(f1, tp2, i);
212 	    			} else {
213 	    				CCOPY_LIST(f2, tp2, b);
214 	    				CCOPY_ELT(f1, tp2, i);
215 	    			}
216 	    		} else {
217 	    			if (iflag) {
218 	    				ICOPY_LIST(f1, tp2, b);
219 	    				ICOPY_ELT(f2, tp2, i);
220 	    			} else {
221 	    				CCOPY_LIST(f1, tp2, b);
222 	    				CCOPY_ELT(f2, tp2, i);
223 	    			}
224 	    		}
225 	    	}
226 	    	if (f2 < l2) {
227 	    		if (iflag)
228 	    			ICOPY_LIST(f2, tp2, l2);
229 	    		else
230 	    			CCOPY_LIST(f2, tp2, l2);
231 	    	} else if (f1 < l1) {
232 	    		if (iflag)
233 	    			ICOPY_LIST(f1, tp2, l1);
234 	    		else
235 	    			CCOPY_LIST(f1, tp2, l1);
236 	    	}
237 	    	*p1 = l2;
238 	    }
239 	    tp2 = list1;	/* swap list1, list2 */
240 	    list1 = list2;
241 	    list2 = tp2;
242 	    last = list2 + nmemb*size;
243 	}
244 	if (base == list2) {
245 		memmove(list2, list1, nmemb*size);
246 		list2 = list1;
247 	}
248 	free(list2);
249 	return (0);
250 }
251 
252 #define	swap(a, b) {					\
253 		s = b;					\
254 		i = size;				\
255 		do {					\
256 			tmp = *a; *a++ = *s; *s++ = tmp; \
257 		} while (--i);				\
258 		a -= size;				\
259 	}
260 #define reverse(bot, top) {				\
261 	s = top;					\
262 	do {						\
263 		i = size;				\
264 		do {					\
265 			tmp = *bot; *bot++ = *s; *s++ = tmp; \
266 		} while (--i);				\
267 		s -= size2;				\
268 	} while(bot < s);				\
269 }
270 
271 /*
272  * Optional hybrid natural/pairwise first pass.  Eats up list1 in runs of
273  * increasing order, list2 in a corresponding linked list.  Checks for runs
274  * when THRESHOLD/2 pairs compare with same sense.  (Only used when NATURAL
275  * is defined.  Otherwise simple pairwise merging is used.)
276  */
277 void
278 setup(list1, list2, n, size, cmp)
279 	size_t n, size;
280 	int (*cmp) __P((const void *, const void *));
281 	u_char *list1, *list2;
282 {
283 	int i, length, size2, tmp, sense;
284 	u_char *f1, *f2, *s, *l2, *last, *p2;
285 
286 	size2 = size*2;
287 	if (n <= 5) {
288 		insertionsort(list1, n, size, cmp);
289 		*EVAL(list2) = (u_char*) list2 + n*size;
290 		return;
291 	}
292 	/*
293 	 * Avoid running pointers out of bounds; limit n to evens
294 	 * for simplicity.
295 	 */
296 	i = 4 + (n & 1);
297 	insertionsort(list1 + (n - i) * size, i, size, cmp);
298 	last = list1 + size * (n - i);
299 	*EVAL(list2 + (last - list1)) = list2 + n * size;
300 
301 #ifdef NATURAL
302 	p2 = list2;
303 	f1 = list1;
304 	sense = (cmp(f1, f1 + size) > 0);
305 	for (; f1 < last; sense = !sense) {
306 		length = 2;
307 					/* Find pairs with same sense. */
308 		for (f2 = f1 + size2; f2 < last; f2 += size2) {
309 			if ((cmp(f2, f2+ size) > 0) != sense)
310 				break;
311 			length += 2;
312 		}
313 		if (length < THRESHOLD) {		/* Pairwise merge */
314 			do {
315 				p2 = *EVAL(p2) = f1 + size2 - list1 + list2;
316 				if (sense > 0)
317 					swap (f1, f1 + size);
318 			} while ((f1 += size2) < f2);
319 		} else {				/* Natural merge */
320 			l2 = f2;
321 			for (f2 = f1 + size2; f2 < l2; f2 += size2) {
322 				if ((cmp(f2-size, f2) > 0) != sense) {
323 					p2 = *EVAL(p2) = f2 - list1 + list2;
324 					if (sense > 0)
325 						reverse(f1, f2-size);
326 					f1 = f2;
327 				}
328 			}
329 			if (sense > 0)
330 				reverse (f1, f2-size);
331 			f1 = f2;
332 			if (f2 < last || cmp(f2 - size, f2) > 0)
333 				p2 = *EVAL(p2) = f2 - list1 + list2;
334 			else
335 				p2 = *EVAL(p2) = list2 + n*size;
336 		}
337 	}
338 #else		/* pairwise merge only. */
339 	for (f1 = list1, p2 = list2; f1 < last; f1 += size2) {
340 		p2 = *EVAL(p2) = p2 + size2;
341 		if (cmp (f1, f1 + size) > 0)
342 			swap(f1, f1 + size);
343 	}
344 #endif /* NATURAL */
345 }
346 
347 /*
348  * This is to avoid out-of-bounds addresses in sorting the
349  * last 4 elements.
350  */
351 static void
352 insertionsort(a, n, size, cmp)
353 	u_char *a;
354 	size_t n, size;
355 	int (*cmp) __P((const void *, const void *));
356 {
357 	u_char *ai, *s, *t, *u, tmp;
358 	int i;
359 
360 	for (ai = a+size; --n >= 1; ai += size)
361 		for (t = ai; t > a; t -= size) {
362 			u = t - size;
363 			if (cmp(u, t) <= 0)
364 				break;
365 			swap(u, t);
366 		}
367 }
368