xref: /freebsd/lib/libc/stdlib/heapsort.c (revision dc36d6f9bb1753f3808552f3afd30eda9a7b206a)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * Copyright (c) 2014 David T. Chisnall
7  * All rights reserved.
8  *
9  * This code is derived from software contributed to Berkeley by
10  * Ronnie Kon at Mindcraft Inc., Kevin Lew and Elmer Yglesias.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. 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 #include <errno.h>
38 #include <stddef.h>
39 #include <stdlib.h>
40 
41 #ifdef I_AM_HEAPSORT_B
42 #include "block_abi.h"
43 #define COMPAR(x, y) CALL_BLOCK(compar, x, y)
44 typedef DECLARE_BLOCK(int, heapsort_block, const void *, const void *);
45 #else
46 #define COMPAR(x, y) compar(x, y)
47 #endif
48 
49 /*
50  * Swap two areas of size number of bytes.  Although qsort(3) permits random
51  * blocks of memory to be sorted, sorting pointers is almost certainly the
52  * common case (and, were it not, could easily be made so).  Regardless, it
53  * isn't worth optimizing; the SWAP's get sped up by the cache, and pointer
54  * arithmetic gets lost in the time required for comparison function calls.
55  */
56 #define	SWAP(a, b, count, size, tmp) { \
57 	count = size; \
58 	do { \
59 		tmp = *a; \
60 		*a++ = *b; \
61 		*b++ = tmp; \
62 	} while (--count); \
63 }
64 
65 /* Copy one block of size size to another. */
66 #define COPY(a, b, count, size, tmp1, tmp2) { \
67 	count = size; \
68 	tmp1 = a; \
69 	tmp2 = b; \
70 	do { \
71 		*tmp1++ = *tmp2++; \
72 	} while (--count); \
73 }
74 
75 /*
76  * Build the list into a heap, where a heap is defined such that for
77  * the records K1 ... KN, Kj/2 >= Kj for 1 <= j/2 <= j <= N.
78  *
79  * There two cases.  If j == nmemb, select largest of Ki and Kj.  If
80  * j < nmemb, select largest of Ki, Kj and Kj+1.
81  */
82 #define CREATE(initval, nmemb, par_i, child_i, par, child, size, count, tmp) { \
83 	for (par_i = initval; (child_i = par_i * 2) <= nmemb; \
84 	    par_i = child_i) { \
85 		child = base + child_i * size; \
86 		if (child_i < nmemb && COMPAR(child, child + size) < 0) { \
87 			child += size; \
88 			++child_i; \
89 		} \
90 		par = base + par_i * size; \
91 		if (COMPAR(child, par) <= 0) \
92 			break; \
93 		SWAP(par, child, count, size, tmp); \
94 	} \
95 }
96 
97 /*
98  * Select the top of the heap and 'heapify'.  Since by far the most expensive
99  * action is the call to the compar function, a considerable optimization
100  * in the average case can be achieved due to the fact that k, the displaced
101  * elememt, is usually quite small, so it would be preferable to first
102  * heapify, always maintaining the invariant that the larger child is copied
103  * over its parent's record.
104  *
105  * Then, starting from the *bottom* of the heap, finding k's correct place,
106  * again maintianing the invariant.  As a result of the invariant no element
107  * is 'lost' when k is assigned its correct place in the heap.
108  *
109  * The time savings from this optimization are on the order of 15-20% for the
110  * average case. See Knuth, Vol. 3, page 158, problem 18.
111  *
112  * XXX Don't break the #define SELECT line, below.  Reiser cpp gets upset.
113  */
114 #define SELECT(par_i, child_i, nmemb, par, child, size, k, count, tmp1, tmp2) { \
115 	for (par_i = 1; (child_i = par_i * 2) <= nmemb; par_i = child_i) { \
116 		child = base + child_i * size; \
117 		if (child_i < nmemb && COMPAR(child, child + size) < 0) { \
118 			child += size; \
119 			++child_i; \
120 		} \
121 		par = base + par_i * size; \
122 		COPY(par, child, count, size, tmp1, tmp2); \
123 	} \
124 	for (;;) { \
125 		child_i = par_i; \
126 		par_i = child_i / 2; \
127 		child = base + child_i * size; \
128 		par = base + par_i * size; \
129 		if (child_i == 1 || COMPAR(k, par) < 0) { \
130 			COPY(child, k, count, size, tmp1, tmp2); \
131 			break; \
132 		} \
133 		COPY(child, par, count, size, tmp1, tmp2); \
134 	} \
135 }
136 
137 #ifdef I_AM_HEAPSORT_B
138 int heapsort_b(void *, size_t, size_t, heapsort_block);
139 #else
140 int heapsort(void *, size_t, size_t,
141     int (*)(const void *, const void *));
142 #endif
143 /*
144  * Heapsort -- Knuth, Vol. 3, page 145.  Runs in O (N lg N), both average
145  * and worst.  While heapsort is faster than the worst case of quicksort,
146  * the BSD quicksort does median selection so that the chance of finding
147  * a data set that will trigger the worst case is nonexistent.  Heapsort's
148  * only advantage over quicksort is that it requires little additional memory.
149  */
150 #ifdef I_AM_HEAPSORT_B
151 int
heapsort_b(void * vbase,size_t nmemb,size_t size,heapsort_block compar)152 heapsort_b(void *vbase, size_t nmemb, size_t size, heapsort_block compar)
153 #else
154 int
155 heapsort(void *vbase, size_t nmemb, size_t size,
156     int (*compar)(const void *, const void *))
157 #endif
158 {
159 	size_t cnt, i, j, l;
160 	char tmp, *tmp1, *tmp2;
161 	char *base, *k, *p, *t;
162 
163 	if (nmemb <= 1)
164 		return (0);
165 
166 	if (!size) {
167 		errno = EINVAL;
168 		return (-1);
169 	}
170 
171 	if ((k = malloc(size)) == NULL)
172 		return (-1);
173 
174 	/*
175 	 * Items are numbered from 1 to nmemb, so offset from size bytes
176 	 * below the starting address.
177 	 */
178 	base = (char *)vbase - size;
179 
180 	for (l = nmemb / 2 + 1; --l;)
181 		CREATE(l, nmemb, i, j, t, p, size, cnt, tmp);
182 
183 	/*
184 	 * For each element of the heap, save the largest element into its
185 	 * final slot, save the displaced element (k), then recreate the
186 	 * heap.
187 	 */
188 	while (nmemb > 1) {
189 		COPY(k, base + nmemb * size, cnt, size, tmp1, tmp2);
190 		COPY(base + nmemb * size, base + size, cnt, size, tmp1, tmp2);
191 		--nmemb;
192 		SELECT(i, j, nmemb, t, p, size, k, cnt, tmp1, tmp2);
193 	}
194 	free(k);
195 	return (0);
196 }
197