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