xref: /openbsd/lib/libc/stdlib/merge.c (revision 404b540a)
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, int (*)());
55 static void insertionsort(u_char *, size_t, size_t, int (*)());
56 
57 #define ISIZE sizeof(int)
58 #define PSIZE sizeof(u_char *)
59 #define ICOPY_LIST(src, dst, last)				\
60 	do							\
61 	*(int*)dst = *(int*)src, src += ISIZE, dst += ISIZE;	\
62 	while(src < last)
63 #define ICOPY_ELT(src, dst, i)					\
64 	do							\
65 	*(int*) dst = *(int*) src, src += ISIZE, dst += ISIZE;	\
66 	while (i -= ISIZE)
67 
68 #define CCOPY_LIST(src, dst, last)		\
69 	do					\
70 		*dst++ = *src++;		\
71 	while (src < last)
72 #define CCOPY_ELT(src, dst, i)			\
73 	do					\
74 		*dst++ = *src++;		\
75 	while (i -= 1)
76 
77 /*
78  * Find the next possible pointer head.  (Trickery for forcing an array
79  * to do double duty as a linked list when objects do not align with word
80  * boundaries.
81  */
82 /* Assumption: PSIZE is a power of 2. */
83 #define EVAL(p) (u_char **)						\
84 	((u_char *)0 +							\
85 	    (((u_char *)p + PSIZE - 1 - (u_char *) 0) & ~(PSIZE - 1)))
86 
87 /*
88  * Arguments are as for qsort.
89  */
90 int
91 mergesort(void *base, size_t nmemb, size_t size,
92     int (*cmp)(const void *, const void *))
93 {
94 	int i, sense;
95 	int big, iflag;
96 	u_char *f1, *f2, *t, *b, *tp2, *q, *l1, *l2;
97 	u_char *list2, *list1, *p2, *p, *last, **p1;
98 
99 	if (size < PSIZE / 2) {		/* Pointers must fit into 2 * size. */
100 		errno = EINVAL;
101 		return (-1);
102 	}
103 
104 	/*
105 	 * XXX
106 	 * Stupid subtraction for the Cray.
107 	 */
108 	iflag = 0;
109 	if (!(size % ISIZE) && !(((char *)base - (char *)0) % ISIZE))
110 		iflag = 1;
111 
112 	if ((list2 = malloc(nmemb * size + PSIZE)) == NULL)
113 		return (-1);
114 
115 	list1 = base;
116 	setup(list1, list2, nmemb, size, cmp);
117 	last = list2 + nmemb * size;
118 	i = big = 0;
119 	while (*EVAL(list2) != last) {
120 	    l2 = list1;
121 	    p1 = EVAL(list1);
122 	    for (tp2 = p2 = list2; p2 != last; p1 = EVAL(l2)) {
123 	    	p2 = *EVAL(p2);
124 	    	f1 = l2;
125 	    	f2 = l1 = list1 + (p2 - list2);
126 	    	if (p2 != last)
127 	    		p2 = *EVAL(p2);
128 	    	l2 = list1 + (p2 - list2);
129 	    	while (f1 < l1 && f2 < l2) {
130 	    		if ((*cmp)(f1, f2) <= 0) {
131 	    			q = f2;
132 	    			b = f1, t = l1;
133 	    			sense = -1;
134 	    		} else {
135 	    			q = f1;
136 	    			b = f2, t = l2;
137 	    			sense = 0;
138 	    		}
139 	    		if (!big) {	/* here i = 0 */
140 	    			while ((b += size) < t && cmp(q, b) >sense)
141 	    				if (++i == 6) {
142 	    					big = 1;
143 	    					goto EXPONENTIAL;
144 	    				}
145 	    		} else {
146 EXPONENTIAL:	    		for (i = size; ; i <<= 1)
147 	    				if ((p = (b + i)) >= t) {
148 	    					if ((p = t - size) > b &&
149 						    (*cmp)(q, p) <= sense)
150 	    						t = p;
151 	    					else
152 	    						b = p;
153 	    					break;
154 	    				} else if ((*cmp)(q, p) <= sense) {
155 	    					t = p;
156 	    					if (i == size)
157 	    						big = 0;
158 	    					goto FASTCASE;
159 	    				} else
160 	    					b = p;
161 		    		while (t > b+size) {
162 	    				i = (((t - b) / size) >> 1) * size;
163 	    				if ((*cmp)(q, p = b + i) <= sense)
164 	    					t = p;
165 	    				else
166 	    					b = p;
167 	    			}
168 	    			goto COPY;
169 FASTCASE:	    		while (i > size)
170 	    				if ((*cmp)(q,
171 	    					p = b + (i >>= 1)) <= sense)
172 	    					t = p;
173 	    				else
174 	    					b = p;
175 COPY:	    			b = t;
176 	    		}
177 	    		i = size;
178 	    		if (q == f1) {
179 	    			if (iflag) {
180 	    				ICOPY_LIST(f2, tp2, b);
181 	    				ICOPY_ELT(f1, tp2, i);
182 	    			} else {
183 	    				CCOPY_LIST(f2, tp2, b);
184 	    				CCOPY_ELT(f1, tp2, i);
185 	    			}
186 	    		} else {
187 	    			if (iflag) {
188 	    				ICOPY_LIST(f1, tp2, b);
189 	    				ICOPY_ELT(f2, tp2, i);
190 	    			} else {
191 	    				CCOPY_LIST(f1, tp2, b);
192 	    				CCOPY_ELT(f2, tp2, i);
193 	    			}
194 	    		}
195 	    	}
196 	    	if (f2 < l2) {
197 	    		if (iflag)
198 	    			ICOPY_LIST(f2, tp2, l2);
199 	    		else
200 	    			CCOPY_LIST(f2, tp2, l2);
201 	    	} else if (f1 < l1) {
202 	    		if (iflag)
203 	    			ICOPY_LIST(f1, tp2, l1);
204 	    		else
205 	    			CCOPY_LIST(f1, tp2, l1);
206 	    	}
207 	    	*p1 = l2;
208 	    }
209 	    tp2 = list1;	/* swap list1, list2 */
210 	    list1 = list2;
211 	    list2 = tp2;
212 	    last = list2 + nmemb*size;
213 	}
214 	if (base == list2) {
215 		memmove(list2, list1, nmemb*size);
216 		list2 = list1;
217 	}
218 	free(list2);
219 	return (0);
220 }
221 
222 #define	swap(a, b) {					\
223 		s = b;					\
224 		i = size;				\
225 		do {					\
226 			tmp = *a; *a++ = *s; *s++ = tmp; \
227 		} while (--i);				\
228 		a -= size;				\
229 	}
230 #define reverse(bot, top) {				\
231 	s = top;					\
232 	do {						\
233 		i = size;				\
234 		do {					\
235 			tmp = *bot; *bot++ = *s; *s++ = tmp; \
236 		} while (--i);				\
237 		s -= size2;				\
238 	} while(bot < s);				\
239 }
240 
241 /*
242  * Optional hybrid natural/pairwise first pass.  Eats up list1 in runs of
243  * increasing order, list2 in a corresponding linked list.  Checks for runs
244  * when THRESHOLD/2 pairs compare with same sense.  (Only used when NATURAL
245  * is defined.  Otherwise simple pairwise merging is used.)
246  */
247 void
248 setup(u_char *list1, u_char *list2, size_t n, size_t size,
249     int (*cmp)(const void *, const void *))
250 {
251 	int i, length, size2, tmp, sense;
252 	u_char *f1, *f2, *s, *l2, *last, *p2;
253 
254 	size2 = size*2;
255 	if (n <= 5) {
256 		insertionsort(list1, n, size, cmp);
257 		*EVAL(list2) = (u_char*) list2 + n*size;
258 		return;
259 	}
260 	/*
261 	 * Avoid running pointers out of bounds; limit n to evens
262 	 * for simplicity.
263 	 */
264 	i = 4 + (n & 1);
265 	insertionsort(list1 + (n - i) * size, i, size, cmp);
266 	last = list1 + size * (n - i);
267 	*EVAL(list2 + (last - list1)) = list2 + n * size;
268 
269 #ifdef NATURAL
270 	p2 = list2;
271 	f1 = list1;
272 	sense = (cmp(f1, f1 + size) > 0);
273 	for (; f1 < last; sense = !sense) {
274 		length = 2;
275 					/* Find pairs with same sense. */
276 		for (f2 = f1 + size2; f2 < last; f2 += size2) {
277 			if ((cmp(f2, f2+ size) > 0) != sense)
278 				break;
279 			length += 2;
280 		}
281 		if (length < THRESHOLD) {		/* Pairwise merge */
282 			do {
283 				p2 = *EVAL(p2) = f1 + size2 - list1 + list2;
284 				if (sense > 0)
285 					swap (f1, f1 + size);
286 			} while ((f1 += size2) < f2);
287 		} else {				/* Natural merge */
288 			l2 = f2;
289 			for (f2 = f1 + size2; f2 < l2; f2 += size2) {
290 				if ((cmp(f2-size, f2) > 0) != sense) {
291 					p2 = *EVAL(p2) = f2 - list1 + list2;
292 					if (sense > 0)
293 						reverse(f1, f2-size);
294 					f1 = f2;
295 				}
296 			}
297 			if (sense > 0)
298 				reverse (f1, f2-size);
299 			f1 = f2;
300 			if (f2 < last || cmp(f2 - size, f2) > 0)
301 				p2 = *EVAL(p2) = f2 - list1 + list2;
302 			else
303 				p2 = *EVAL(p2) = list2 + n*size;
304 		}
305 	}
306 #else		/* pairwise merge only. */
307 	for (f1 = list1, p2 = list2; f1 < last; f1 += size2) {
308 		p2 = *EVAL(p2) = p2 + size2;
309 		if (cmp (f1, f1 + size) > 0)
310 			swap(f1, f1 + size);
311 	}
312 #endif /* NATURAL */
313 }
314 
315 /*
316  * This is to avoid out-of-bounds addresses in sorting the
317  * last 4 elements.
318  */
319 static void
320 insertionsort(u_char *a, size_t n, size_t size,
321     int (*cmp)(const void *, const void *))
322 {
323 	u_char *ai, *s, *t, *u, tmp;
324 	int i;
325 
326 	for (ai = a+size; --n >= 1; ai += size)
327 		for (t = ai; t > a; t -= size) {
328 			u = t - size;
329 			if (cmp(u, t) <= 0)
330 				break;
331 			swap(u, t);
332 		}
333 }
334