1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2007, 2009, 2010 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Balanced tree (BT) data structure.
19 The client should not need to be aware of the form of
20 balancing applied to the balanced tree, as its operation is
21 fully encapsulated. The current implementation is a scapegoat
22 tree. Scapegoat trees have the advantage over many other
23 forms of balanced trees that they do not store any additional
24 information in each node; thus, they are slightly more
25 space-efficient than, say, red-black or AVL trees. Compared
26 to splay trees, scapegoat trees provide guaranteed logarithmic
27 worst-case search time and do not restructure the tree during
30 For information on scapegoat trees, see Galperin and Rivest,
31 "Scapegoat Trees", Proc. 4th ACM-SIAM Symposium on Discrete
32 Algorithms, or <http://en.wikipedia.org/wiki/Scapegoat_tree>,
33 which includes source code and links to other resources, such
34 as the Galperin and Rivest paper.
36 One potentially tricky part of scapegoat tree design is the
37 choice of alpha, which is a real constant that must be greater
38 than 0.5 and less than 1. We must be able to efficiently
39 calculate h_alpha = floor(log(n)/log(1/alpha)) for integer n >
40 0. One way to do so would be to maintain a table relating
41 h_alpha to the minimum value of n that yields that h_alpha.
42 Then, we can track the value of h_alpha(n) in the number of
43 nodes in the tree n as nodes are inserted and deleted.
45 This implementation uses a different approach. We choose
46 alpha = sqrt(2)/2 = 1/sqrt(2) ~= .707. Then, computing
47 h_alpha is a matter of computing a logarithm in base sqrt(2).
48 This is easy: we simply compute twice the base-2 logarithm,
49 then adjust upward by 1 if necessary. See calculate_h_alpha
52 /* These library routines have no external dependencies other
53 than the standard C library.
55 If you add routines in this file, please add a corresponding
56 test to bt-test.c. This test program should achieve 100%
57 coverage of lines and branches in this code, as reported by
64 #include <libpspp/bt.h>
70 #include <libpspp/cast.h>
72 static void rebalance_subtree (struct bt *, struct bt_node *, size_t);
74 static struct bt_node **down_link (struct bt *, struct bt_node *);
75 static inline struct bt_node *sibling (struct bt_node *p);
76 static size_t count_nodes_in_subtree (const struct bt_node *);
78 static inline int floor_log2 (size_t);
79 static inline int calculate_h_alpha (size_t);
81 /* Initializes BT as an empty BT that uses the given COMPARE
82 function, passing in AUX as auxiliary data. */
84 bt_init (struct bt *bt, bt_compare_func *compare, const void *aux)
87 bt->compare = compare;
93 /* Inserts the given NODE into BT.
94 Returns a null pointer if successful.
95 Returns the existing node already in BT equal to NODE, on
98 bt_insert (struct bt *bt, struct bt_node *node)
102 node->down[0] = NULL;
103 node->down[1] = NULL;
105 if (bt->root == NULL)
112 struct bt_node *p = bt->root;
117 cmp = bt->compare (node, p, bt->aux);
123 if (p->down[dir] == NULL)
134 if (bt->size > bt->max_size)
135 bt->max_size = bt->size;
137 if (depth > calculate_h_alpha (bt->size))
139 /* We use the "alternative" method of finding a scapegoat
140 node described by Galperin and Rivest. */
141 struct bt_node *s = node;
148 size += 1 + count_nodes_in_subtree (sibling (s));
150 if (i > calculate_h_alpha (size))
152 rebalance_subtree (bt, s, size);
158 rebalance_subtree (bt, bt->root, bt->size);
159 bt->max_size = bt->size;
167 /* Deletes P from BT. */
169 bt_delete (struct bt *bt, struct bt_node *p)
171 struct bt_node **q = down_link (bt, p);
172 struct bt_node *r = p->down[1];
179 else if (r->down[0] == NULL)
181 r->down[0] = p->down[0];
184 if (r->down[0] != NULL)
189 struct bt_node *s = r->down[0];
190 while (s->down[0] != NULL)
193 r->down[0] = s->down[1];
194 s->down[0] = p->down[0];
195 s->down[1] = p->down[1];
197 if (s->down[0] != NULL)
201 if (r->down[0] != NULL)
206 /* We approximate .707 as .75 here. This is conservative: it
207 will cause us to do a little more rebalancing than strictly
208 necessary to maintain the scapegoat tree's height
210 if (bt->size < bt->max_size * 3 / 4 && bt->size > 0)
212 rebalance_subtree (bt, bt->root, bt->size);
213 bt->max_size = bt->size;
217 /* Returns the node with minimum value in BT, or a null pointer
220 bt_first (const struct bt *bt)
222 struct bt_node *p = bt->root;
224 while (p->down[0] != NULL)
229 /* Returns the node with maximum value in BT, or a null pointer
232 bt_last (const struct bt *bt)
234 struct bt_node *p = bt->root;
236 while (p->down[1] != NULL)
241 /* Searches BT for a node equal to TARGET.
242 Returns the node if found, or a null pointer otherwise. */
244 bt_find (const struct bt *bt, const struct bt_node *target)
246 const struct bt_node *p;
249 for (p = bt->root; p != NULL; p = p->down[cmp > 0])
251 cmp = bt->compare (target, p, bt->aux);
253 return CONST_CAST (struct bt_node *, p);
259 /* Searches BT for, and returns, the first node in in-order whose
260 value is greater than or equal to TARGET. Returns a null
261 pointer if all nodes in BT are less than TARGET.
263 Another way to look at the return value is that it is the node
264 that would be returned by "bt_next (BT, TARGET)" if TARGET
265 were inserted in BT (assuming that TARGET would not be a
268 bt_find_ge (const struct bt *bt, const struct bt_node *target)
270 const struct bt_node *p = bt->root;
271 const struct bt_node *q = NULL;
274 int cmp = bt->compare (target, p, bt->aux);
286 return CONST_CAST (struct bt_node *, q);
289 /* Searches BT for, and returns, the last node in in-order whose
290 value is less than or equal to TARGET, which should not be in
291 BT. Returns a null pointer if all nodes in BT are greater
294 Another way to look at the return value is that it is the node
295 that would be returned by "bt_prev (BT, TARGET)" if TARGET
296 were inserted in BT (assuming that TARGET would not be a
299 bt_find_le (const struct bt *bt, const struct bt_node *target)
301 const struct bt_node *p = bt->root;
302 const struct bt_node *q = NULL;
305 int cmp = bt->compare (target, p, bt->aux);
317 return CONST_CAST (struct bt_node *, q);
320 /* Returns the node in BT following P in in-order.
321 If P is null, returns the minimum node in BT.
322 Returns a null pointer if P is the maximum node in BT or if P
323 is null and BT is empty. */
325 bt_next (const struct bt *bt, const struct bt_node *p)
328 return bt_first (bt);
329 else if (p->down[1] == NULL)
332 for (q = p->up; ; p = q, q = q->up)
333 if (q == NULL || p == q->down[0])
339 while (p->down[0] != NULL)
341 return CONST_CAST (struct bt_node *, p);
345 /* Returns the node in BT preceding P in in-order.
346 If P is null, returns the maximum node in BT.
347 Returns a null pointer if P is the minimum node in BT or if P
348 is null and BT is empty. */
350 bt_prev (const struct bt *bt, const struct bt_node *p)
354 else if (p->down[0] == NULL)
357 for (q = p->up; ; p = q, q = q->up)
358 if (q == NULL || p == q->down[1])
364 while (p->down[1] != NULL)
366 return CONST_CAST (struct bt_node *, p);
370 /* Moves P around in BT to compensate for its key having
371 changed. Returns a null pointer if successful. If P's new
372 value is equal to that of some other node in BT, returns the
373 other node after removing P from BT.
375 This function is an optimization only if it is likely that P
376 can actually retain its relative position in BT, e.g. its key
377 has only been adjusted slightly. Otherwise, it is more
378 efficient to simply remove P from BT, change its key, and
381 It is not safe to update more than one node's key, then to
382 call this function for each node. Instead, update a single
383 node's key, call this function, update another node's key, and
384 so on. Alternatively, remove all affected nodes from the
385 tree, update their keys, then re-insert all of them. */
387 bt_changed (struct bt *bt, struct bt_node *p)
389 struct bt_node *prev = bt_prev (bt, p);
390 struct bt_node *next = bt_next (bt, p);
392 if ((prev != NULL && bt->compare (prev, p, bt->aux) >= 0)
393 || (next != NULL && bt->compare (p, next, bt->aux) >= 0))
396 return bt_insert (bt, p);
401 /* BT nodes may be moved around in memory as necessary, e.g. as
402 the result of an realloc operation on a block that contains a
403 node. Once this is done, call this function passing node P
404 that was moved and its BT before attempting any other
407 It is not safe to move more than one node, then to call this
408 function for each node. Instead, move a single node, call
409 this function, move another node, and so on. Alternatively,
410 remove all affected nodes from the tree, move them, then
411 re-insert all of them. */
413 bt_moved (struct bt *bt, struct bt_node *p)
417 int d = p->up->down[0] == NULL || bt->compare (p, p->up, bt->aux) > 0;
422 if (p->down[0] != NULL)
424 if (p->down[1] != NULL)
430 This algorithm is from Q. F. Stout and B. L. Warren, "Tree
431 Rebalancing in Optimal Time and Space", CACM 29(1986):9,
432 pp. 902-908. It uses O(N) time and O(1) space to rebalance a
433 subtree that contains N nodes. */
435 static void tree_to_vine (struct bt_node **);
436 static void vine_to_tree (struct bt_node **, size_t count);
438 /* Rebalances the subtree in BT rooted at SUBTREE, which contains
439 exactly COUNT nodes. */
441 rebalance_subtree (struct bt *bt, struct bt_node *subtree, size_t count)
443 struct bt_node *up = subtree->up;
444 struct bt_node **q = down_link (bt, subtree);
446 vine_to_tree (q, count);
450 /* Converts the subtree rooted at *Q into a vine (a binary search
451 tree in which all the right links are null), and updates *Q to
452 point to the new root of the subtree. */
454 tree_to_vine (struct bt_node **q)
456 struct bt_node *p = *q;
458 if (p->down[1] == NULL)
465 struct bt_node *r = p->down[1];
466 p->down[1] = r->down[0];
473 /* Performs a compression transformation COUNT times, starting at
474 *Q, and updates *Q to point to the new root of the subtree. */
476 compress (struct bt_node **q, unsigned long count)
480 struct bt_node *red = *q;
481 struct bt_node *black = red->down[0];
484 red->down[0] = black->down[1];
485 black->down[1] = red;
487 if (red->down[0] != NULL)
488 red->down[0]->up = red;
493 /* Converts the vine rooted at *Q, which contains exactly COUNT
494 nodes, into a balanced tree, and updates *Q to point to the
495 new root of the balanced tree. */
497 vine_to_tree (struct bt_node **q, size_t count)
499 size_t leaf_nodes = count + 1 - ((size_t) 1 << floor_log2 (count + 1));
500 size_t vine_nodes = count - leaf_nodes;
502 compress (q, leaf_nodes);
503 while (vine_nodes > 1)
506 compress (q, vine_nodes);
508 while ((*q)->down[0] != NULL)
510 (*q)->down[0]->up = *q;
515 /* Other binary tree helper functions. */
517 /* Returns the address of the pointer that points down to P
519 static struct bt_node **
520 down_link (struct bt *bt, struct bt_node *p)
522 struct bt_node *q = p->up;
523 return q != NULL ? &q->down[q->down[0] != p] : &bt->root;
526 /* Returns node P's sibling; that is, the other child of its
527 parent. P must not be the root. */
528 static inline struct bt_node *
529 sibling (struct bt_node *p)
531 struct bt_node *q = p->up;
532 return q->down[q->down[0] == p];
535 /* Returns the number of nodes in the given SUBTREE. */
537 count_nodes_in_subtree (const struct bt_node *subtree)
539 /* This is an in-order traversal modified to iterate only the
544 const struct bt_node *p = subtree;
545 while (p->down[0] != NULL)
550 if (p->down[1] != NULL)
553 while (p->down[0] != NULL)
560 const struct bt_node *q;
577 /* Returns the number of high-order 0-bits in X.
578 Undefined if X is zero. */
580 count_leading_zeros (size_t x)
583 #if SIZE_MAX > ULONG_MAX
584 return __builtin_clzll (x);
585 #elif SIZE_MAX > UINT_MAX
586 return __builtin_clzl (x);
588 return __builtin_clz (x);
591 /* This algorithm is from _Hacker's Delight_ section 5.3. */
595 #define COUNT_STEP(BITS) \
603 n = sizeof (size_t) * CHAR_BIT;
604 #if SIZE_MAX >> 31 >> 31 >> 2
607 #if SIZE_MAX >> 31 >> 1
615 return y != 0 ? n - 2 : n - x;
619 /* Returns floor(log2(x)).
620 Undefined if X is zero. */
622 floor_log2 (size_t x)
624 return sizeof (size_t) * CHAR_BIT - 1 - count_leading_zeros (x);
627 /* Returns floor(pow(sqrt(2), x * 2 + 1)).
628 Defined for X from 0 up to the number of bits in size_t minus
633 /* These constants are sqrt(2) multiplied by 2**63 or 2**31,
634 respectively, and then rounded to nearest. */
635 #if SIZE_MAX >> 31 >> 1
636 return (UINT64_C(0xb504f333f9de6484) >> (63 - x)) + 1;
638 return (0xb504f334 >> (31 - x)) + 1;
642 /* Returns floor(log(n)/log(sqrt(2))).
643 Undefined if N is 0. */
645 calculate_h_alpha (size_t n)
647 int log2 = floor_log2 (n);
649 /* The correct answer is either 2 * log2 or one more. So we
650 see if n >= pow(sqrt(2), 2 * log2 + 1) and if so, add 1. */
651 return (2 * log2) + (n >= pow_sqrt2 (log2));