]> git.saurik.com Git - apple/libc.git/blame - stdlib/heapsort.c
Libc-262.2.12.tar.gz
[apple/libc.git] / stdlib / heapsort.c
CommitLineData
e9ce8d39
A
1/*
2 * Copyright (c) 1999 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
734aad71 6 * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
e9ce8d39 7 *
734aad71
A
8 * This file contains Original Code and/or Modifications of Original Code
9 * as defined in and that are subject to the Apple Public Source License
10 * Version 2.0 (the 'License'). You may not use this file except in
11 * compliance with the License. Please obtain a copy of the License at
12 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * file.
14 *
15 * The Original Code and all software distributed under the License are
16 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
e9ce8d39
A
17 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
18 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
734aad71
A
19 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
20 * Please see the License for the specific language governing rights and
21 * limitations under the License.
e9ce8d39
A
22 *
23 * @APPLE_LICENSE_HEADER_END@
24 */
25/*
26 * Copyright (c) 1991, 1993
27 * The Regents of the University of California. All rights reserved.
28 *
29 * This code is derived from software contributed to Berkeley by
30 * Ronnie Kon at Mindcraft Inc., Kevin Lew and Elmer Yglesias.
31 *
32 * Redistribution and use in source and binary forms, with or without
33 * modification, are permitted provided that the following conditions
34 * are met:
35 * 1. Redistributions of source code must retain the above copyright
36 * notice, this list of conditions and the following disclaimer.
37 * 2. Redistributions in binary form must reproduce the above copyright
38 * notice, this list of conditions and the following disclaimer in the
39 * documentation and/or other materials provided with the distribution.
40 * 3. All advertising materials mentioning features or use of this software
41 * must display the following acknowledgement:
42 * This product includes software developed by the University of
43 * California, Berkeley and its contributors.
44 * 4. Neither the name of the University nor the names of its contributors
45 * may be used to endorse or promote products derived from this software
46 * without specific prior written permission.
47 *
48 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58 * SUCH DAMAGE.
59 */
60
61
62#include <sys/types.h>
63#include <errno.h>
64#include <stdlib.h>
65#include <stddef.h>
66
67/*
68 * Swap two areas of size number of bytes. Although qsort(3) permits random
69 * blocks of memory to be sorted, sorting pointers is almost certainly the
70 * common case (and, were it not, could easily be made so). Regardless, it
71 * isn't worth optimizing; the SWAP's get sped up by the cache, and pointer
72 * arithmetic gets lost in the time required for comparison function calls.
73 */
74#define SWAP(a, b, count, size, tmp) { \
75 count = size; \
76 do { \
77 tmp = *a; \
78 *a++ = *b; \
79 *b++ = tmp; \
80 } while (--count); \
81}
82
83/* Copy one block of size size to another. */
84#define COPY(a, b, count, size, tmp1, tmp2) { \
85 count = size; \
86 tmp1 = a; \
87 tmp2 = b; \
88 do { \
89 *tmp1++ = *tmp2++; \
90 } while (--count); \
91}
92
93/*
94 * Build the list into a heap, where a heap is defined such that for
95 * the records K1 ... KN, Kj/2 >= Kj for 1 <= j/2 <= j <= N.
96 *
97 * There two cases. If j == nmemb, select largest of Ki and Kj. If
98 * j < nmemb, select largest of Ki, Kj and Kj+1.
99 */
100#define CREATE(initval, nmemb, par_i, child_i, par, child, size, count, tmp) { \
101 for (par_i = initval; (child_i = par_i * 2) <= nmemb; \
102 par_i = child_i) { \
103 child = base + child_i * size; \
104 if (child_i < nmemb && compar(child, child + size) < 0) { \
105 child += size; \
106 ++child_i; \
107 } \
108 par = base + par_i * size; \
109 if (compar(child, par) <= 0) \
110 break; \
111 SWAP(par, child, count, size, tmp); \
112 } \
113}
114
115/*
116 * Select the top of the heap and 'heapify'. Since by far the most expensive
117 * action is the call to the compar function, a considerable optimization
118 * in the average case can be achieved due to the fact that k, the displaced
119 * elememt, is ususally quite small, so it would be preferable to first
120 * heapify, always maintaining the invariant that the larger child is copied
121 * over its parent's record.
122 *
123 * Then, starting from the *bottom* of the heap, finding k's correct place,
124 * again maintianing the invariant. As a result of the invariant no element
125 * is 'lost' when k is assigned its correct place in the heap.
126 *
127 * The time savings from this optimization are on the order of 15-20% for the
128 * average case. See Knuth, Vol. 3, page 158, problem 18.
129 *
130 * XXX Don't break the #define SELECT line, below. Reiser cpp gets upset.
131 */
132#define SELECT(par_i, child_i, nmemb, par, child, size, k, count, tmp1, tmp2) { \
133 for (par_i = 1; (child_i = par_i * 2) <= nmemb; par_i = child_i) { \
134 child = base + child_i * size; \
135 if (child_i < nmemb && compar(child, child + size) < 0) { \
136 child += size; \
137 ++child_i; \
138 } \
139 par = base + par_i * size; \
140 COPY(par, child, count, size, tmp1, tmp2); \
141 } \
142 for (;;) { \
143 child_i = par_i; \
144 par_i = child_i / 2; \
145 child = base + child_i * size; \
146 par = base + par_i * size; \
147 if (child_i == 1 || compar(k, par) < 0) { \
148 COPY(child, k, count, size, tmp1, tmp2); \
149 break; \
150 } \
151 COPY(child, par, count, size, tmp1, tmp2); \
152 } \
153}
154
155/*
156 * Heapsort -- Knuth, Vol. 3, page 145. Runs in O (N lg N), both average
157 * and worst. While heapsort is faster than the worst case of quicksort,
158 * the BSD quicksort does median selection so that the chance of finding
159 * a data set that will trigger the worst case is nonexistent. Heapsort's
160 * only advantage over quicksort is that it requires little additional memory.
161 */
162int
163heapsort(vbase, nmemb, size, compar)
164 void *vbase;
165 size_t nmemb, size;
166 int (*compar) __P((const void *, const void *));
167{
168 register int cnt, i, j, l;
169 register char tmp, *tmp1, *tmp2;
170 char *base, *k, *p, *t;
171
172 if (nmemb <= 1)
173 return (0);
174
175 if (!size) {
176 errno = EINVAL;
177 return (-1);
178 }
179
180 if ((k = malloc(size)) == NULL)
181 return (-1);
182
183 /*
184 * Items are numbered from 1 to nmemb, so offset from size bytes
185 * below the starting address.
186 */
187 base = (char *)vbase - size;
188
189 for (l = nmemb / 2 + 1; --l;)
190 CREATE(l, nmemb, i, j, t, p, size, cnt, tmp);
191
192 /*
193 * For each element of the heap, save the largest element into its
194 * final slot, save the displaced element (k), then recreate the
195 * heap.
196 */
197 while (nmemb > 1) {
198 COPY(k, base + nmemb * size, cnt, size, tmp1, tmp2);
199 COPY(base + nmemb * size, base + size, cnt, size, tmp1, tmp2);
200 --nmemb;
201 SELECT(i, j, nmemb, t, p, size, k, cnt, tmp1, tmp2);
202 }
203 free(k);
204 return (0);
205}