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