xref: /freebsd/lib/libc/stdlib/heapsort.c (revision 39ee7a7a6bdd1557b1c3532abf60d139798ac88b)
1 /*-
2  * Copyright (c) 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 2014 David T. Chisnall
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Ronnie Kon at Mindcraft Inc., Kevin Lew and Elmer Yglesias.
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. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #if defined(LIBC_SCCS) && !defined(lint)
36 static char sccsid[] = "@(#)heapsort.c	8.1 (Berkeley) 6/4/93";
37 #endif /* LIBC_SCCS and not lint */
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40 
41 #include <errno.h>
42 #include <stddef.h>
43 #include <stdlib.h>
44 
45 #ifdef I_AM_HEAPSORT_B
46 #include "block_abi.h"
47 #define COMPAR(x, y) CALL_BLOCK(compar, x, y)
48 typedef DECLARE_BLOCK(int, heapsort_block, const void *, const void *);
49 #else
50 #define COMPAR(x, y) compar(x, y)
51 #endif
52 
53 /*
54  * Swap two areas of size number of bytes.  Although qsort(3) permits random
55  * blocks of memory to be sorted, sorting pointers is almost certainly the
56  * common case (and, were it not, could easily be made so).  Regardless, it
57  * isn't worth optimizing; the SWAP's get sped up by the cache, and pointer
58  * arithmetic gets lost in the time required for comparison function calls.
59  */
60 #define	SWAP(a, b, count, size, tmp) { \
61 	count = size; \
62 	do { \
63 		tmp = *a; \
64 		*a++ = *b; \
65 		*b++ = tmp; \
66 	} while (--count); \
67 }
68 
69 /* Copy one block of size size to another. */
70 #define COPY(a, b, count, size, tmp1, tmp2) { \
71 	count = size; \
72 	tmp1 = a; \
73 	tmp2 = b; \
74 	do { \
75 		*tmp1++ = *tmp2++; \
76 	} while (--count); \
77 }
78 
79 /*
80  * Build the list into a heap, where a heap is defined such that for
81  * the records K1 ... KN, Kj/2 >= Kj for 1 <= j/2 <= j <= N.
82  *
83  * There two cases.  If j == nmemb, select largest of Ki and Kj.  If
84  * j < nmemb, select largest of Ki, Kj and Kj+1.
85  */
86 #define CREATE(initval, nmemb, par_i, child_i, par, child, size, count, tmp) { \
87 	for (par_i = initval; (child_i = par_i * 2) <= nmemb; \
88 	    par_i = child_i) { \
89 		child = base + child_i * size; \
90 		if (child_i < nmemb && COMPAR(child, child + size) < 0) { \
91 			child += size; \
92 			++child_i; \
93 		} \
94 		par = base + par_i * size; \
95 		if (COMPAR(child, par) <= 0) \
96 			break; \
97 		SWAP(par, child, count, size, tmp); \
98 	} \
99 }
100 
101 /*
102  * Select the top of the heap and 'heapify'.  Since by far the most expensive
103  * action is the call to the compar function, a considerable optimization
104  * in the average case can be achieved due to the fact that k, the displaced
105  * elememt, is ususally quite small, so it would be preferable to first
106  * heapify, always maintaining the invariant that the larger child is copied
107  * over its parent's record.
108  *
109  * Then, starting from the *bottom* of the heap, finding k's correct place,
110  * again maintianing the invariant.  As a result of the invariant no element
111  * is 'lost' when k is assigned its correct place in the heap.
112  *
113  * The time savings from this optimization are on the order of 15-20% for the
114  * average case. See Knuth, Vol. 3, page 158, problem 18.
115  *
116  * XXX Don't break the #define SELECT line, below.  Reiser cpp gets upset.
117  */
118 #define SELECT(par_i, child_i, nmemb, par, child, size, k, count, tmp1, tmp2) { \
119 	for (par_i = 1; (child_i = par_i * 2) <= nmemb; par_i = child_i) { \
120 		child = base + child_i * size; \
121 		if (child_i < nmemb && COMPAR(child, child + size) < 0) { \
122 			child += size; \
123 			++child_i; \
124 		} \
125 		par = base + par_i * size; \
126 		COPY(par, child, count, size, tmp1, tmp2); \
127 	} \
128 	for (;;) { \
129 		child_i = par_i; \
130 		par_i = child_i / 2; \
131 		child = base + child_i * size; \
132 		par = base + par_i * size; \
133 		if (child_i == 1 || COMPAR(k, par) < 0) { \
134 			COPY(child, k, count, size, tmp1, tmp2); \
135 			break; \
136 		} \
137 		COPY(child, par, count, size, tmp1, tmp2); \
138 	} \
139 }
140 
141 #ifdef I_AM_HEAPSORT_B
142 int heapsort_b(void *, size_t, size_t, heapsort_block);
143 #else
144 int heapsort(void *, size_t, size_t,
145     int (*)(const void *, const void *));
146 #endif
147 /*
148  * Heapsort -- Knuth, Vol. 3, page 145.  Runs in O (N lg N), both average
149  * and worst.  While heapsort is faster than the worst case of quicksort,
150  * the BSD quicksort does median selection so that the chance of finding
151  * a data set that will trigger the worst case is nonexistent.  Heapsort's
152  * only advantage over quicksort is that it requires little additional memory.
153  */
154 #ifdef I_AM_HEAPSORT_B
155 int
156 heapsort_b(void *vbase, size_t nmemb, size_t size, heapsort_block compar)
157 #else
158 int
159 heapsort(void *vbase, size_t nmemb, size_t size,
160     int (*compar)(const void *, const void *))
161 #endif
162 {
163 	size_t cnt, i, j, l;
164 	char tmp, *tmp1, *tmp2;
165 	char *base, *k, *p, *t;
166 
167 	if (nmemb <= 1)
168 		return (0);
169 
170 	if (!size) {
171 		errno = EINVAL;
172 		return (-1);
173 	}
174 
175 	if ((k = malloc(size)) == NULL)
176 		return (-1);
177 
178 	/*
179 	 * Items are numbered from 1 to nmemb, so offset from size bytes
180 	 * below the starting address.
181 	 */
182 	base = (char *)vbase - size;
183 
184 	for (l = nmemb / 2 + 1; --l;)
185 		CREATE(l, nmemb, i, j, t, p, size, cnt, tmp);
186 
187 	/*
188 	 * For each element of the heap, save the largest element into its
189 	 * final slot, save the displaced element (k), then recreate the
190 	 * heap.
191 	 */
192 	while (nmemb > 1) {
193 		COPY(k, base + nmemb * size, cnt, size, tmp1, tmp2);
194 		COPY(base + nmemb * size, base + size, cnt, size, tmp1, tmp2);
195 		--nmemb;
196 		SELECT(i, j, nmemb, t, p, size, k, cnt, tmp1, tmp2);
197 	}
198 	free(k);
199 	return (0);
200 }
201