1 // Copyright (C) 2003 Adam Megacz <adam@ibex.org> all rights reserved.
3 // You may modify, copy, and redistribute this code under the terms of
4 // the GNU Library Public License version 2.1, with the exception of
5 // the portion of clause 6a after the semicolon (aka the "obnoxious
10 // FEATURE: private void intersection() { }
11 // FEATURE: private void union() { }
12 // FEATURE: private void subset() { }
13 // FEATURE: grow if we run out of slots
15 // FEATURE: Add the cached_index stuff back in
17 /** a weight-balanced tree with fake leaves */
18 public class BalancedTree {
19 private static final boolean DEBUG = true;
21 // Instance Variables ///////////////////////////////////////////////////////////////////
23 private int root = 0; ///< the slot of the root element
25 private int cached_index = -1;
26 private int cached_slot = -1;
28 private FinalizationHelper fh;
30 // Public API //////////////////////////////////////////////////////////////////////////
32 /** the number of elements in the tree */
33 public final int treeSize() {
34 synchronized(BalancedTree.class) {
35 return root == 0 ? 0 : size[root];
39 /** clamps index to [0..treeSize()] and inserts object o *before* the specified index */
40 public final void insertNode(int index, Object o) {
41 synchronized(BalancedTree.class) {
42 if(DEBUG) leafCheck();
43 if(o == null) throw new Error("can't insert nulls in the balanced tree");
44 cached_slot = cached_index = -1;
45 if (index < 0) index = 0;
46 if (index > treeSize()) index = treeSize();
47 int arg = allocateSlot(o);
49 insert(index, arg, root, 0, false, false);
51 if(fh == null) fh = new FinalizationHelper(this);
53 left[arg] = right[arg] = parent[arg] = 0;
57 if(DEBUG) leafCheck();
61 /** clamps index to [0..treeSize()-1] and replaces the object at that index with object o */
62 public final void replaceNode(int index, Object o) {
63 synchronized(BalancedTree.class) {
64 if(DEBUG) leafCheck();
65 if(o == null) throw new Error("can't insert nulls in the balanced tree");
66 cached_slot = cached_index = -1;
67 if(root == 0) throw new Error("called replaceNode() on an empty tree");
68 if (index < 0) index = 0;
69 if (index >= treeSize()) index = treeSize() - 1;
70 int arg = allocateSlot(o);
71 insert(index, arg, root, 0, true, false);
73 if(DEBUG) leafCheck();
77 /** returns the index of o; runs in O((log n)^2) time unless cache hit */
78 public final int indexNode(Object o) {
79 synchronized(BalancedTree.class) {
80 if(o == null) return -1;
81 if (cached_slot != -1 && objects[cached_slot] == o) return cached_index;
83 int slot = getSlot(o);
84 if(slot == -1) return -1;
88 // everything to the left is before us so add that to the index
89 index += sizeof(left[slot]);
90 // we are before anything on the right
91 while(left[parent[slot]] == slot) slot = parent[slot];
92 // we end of the first node who isn't on the left, go to the node that has as its child
94 // if we just processed the root we're done
96 // count the node we're currently on towards the index
103 /** returns the object at index; runs in O(log n) time unless cache hit */
104 public final Object getNode(int index) {
105 synchronized(BalancedTree.class) {
106 if(DEBUG) leafCheck();
107 if (index == cached_index) return objects[cached_slot];
109 if (cached_index != -1) {
110 int distance = Math.abs(index - cached_index);
111 // if the in-order distance between the cached node and the
112 // target node is less than log(n), it's probably faster to
114 if ((distance < 16) && ((2 << distance) < treeSize())) {
115 while(cached_index > index) { cached_slot = prev(cached_slot); cached_index--; }
116 while(cached_index < index) { cached_slot = next(cached_slot); cached_index++; }
117 return objects[cached_slot];
121 cached_index = index;
122 cached_slot = get(index, root);
123 return objects[cached_slot];
125 return objects[get(index, root)];
129 /** deletes the object at index, returning the deleted object */
130 public final Object deleteNode(int index) {
131 synchronized(BalancedTree.class) {
132 if(DEBUG) leafCheck();
133 cached_slot = cached_index = -1;
134 // FIXME: left[], right[], size[], and parent[] aren't getting cleared properly somewhere in here where a node had two children
135 int del = delete(index, root, 0);
136 left[del] = right[del] = size[del] = parent[del] = 0;
137 Object ret = objects[del];
140 if(DEBUG) leafCheck();
145 public final void clear() {
146 synchronized(BalancedTree.class) {
147 if(root == 0) return;
148 int i = leftmost(root);
152 left[i] = right[i] = size[i] = parent[i] = 0;
160 // Node Data /////////////////////////////////////////////////////////////////////////
162 private final static int NUM_SLOTS = 64 * 1024;
163 // FEATURE: GROW - private final static int MAX_SLOT_DISTANCE = 32;
166 * Every object inserted into *any* tree gets a "slot" in this
167 * array. The slot is determined by hashcode modulo the length of
168 * the array, with quadradic probing to resolve collisions. NOTE
169 * that the "slot" of a node is NOT the same as its index.
170 * Furthermore, if an object is inserted into multiple trees, that
171 * object will have multiple slots.
173 private static Object[] objects = new Object[NUM_SLOTS];
175 /// These two arrays hold the left and right children of each
176 /// slot; in other words, left[x] is the *slot* of the left child
177 /// of the node in slot x.
179 /// If x has no left child, then left[x] is -1 multiplied by the
180 /// slot of the node that precedes x; if x is the first node, then
181 /// left[x] is 0. The right[] array works the same way.
183 private static int[] left = new int[NUM_SLOTS];
184 private static int[] right = new int[NUM_SLOTS];
186 /// The parent of this node (0 if it is the root node)
187 private static int[] parent = new int[NUM_SLOTS];
189 ///< the number of descendants of this node *including the node itself*
190 private static int[] size = new int[NUM_SLOTS];
193 // Slot Management //////////////////////////////////////////////////////////////////////
195 /** if alloc == false returns the slot holding object o. if alloc is true returns a new slot for obejct o */
196 private int getSlot(Object o, boolean alloc) {
197 // we XOR with our own hashcode so that we don't get tons of
198 // collisions when a single Object is inserted into multiple
200 int dest = Math.abs(o.hashCode() ^ this.hashCode()) % objects.length;
201 Object search = alloc ? null : o;
205 if(dest == 0) dest=1;
206 while (objects[dest] != search || !(alloc || root(dest) == root)) {
207 dest = Math.abs((odest + (plus ? 1 : -1) * tries * tries) % objects.length);
208 if (dest == 0) dest=1;
211 // FEATURE: GROW - if(tries > MAX_SLOT_DISTANCE) return -1;
216 /** returns the slots holding object o */
217 private int getSlot(Object o) { return getSlot(o,false); }
219 /** allocates a new slot holding object o*/
220 private int allocateSlot(Object o) {
221 int slot = getSlot(o, true);
222 // FEATURE: GROW - if(slot == -1) throw new Error("out of slots");
229 // Helpers /////////////////////////////////////////////////////////////////////////
231 // FEATURE: These might be faster if they aren't recursive
232 private final int leftmost(int slot) { return left[slot] <= 0 ? slot : leftmost(left[slot]); }
233 private final int rightmost(int slot) { return right[slot] <= 0 ? slot : rightmost(right[slot]); }
234 private final int sizeof(int slot) { return slot <= 0 ? 0 : size[slot]; }
235 private final int root(int slot) { return parent[slot] == 0 ? slot : root(parent[slot]); }
237 private int next(int node) {
238 if(right[node] > 0) {
240 while(left[node] > 0) node = left[node];
243 int p = parent[node];
244 while(right[p] == node) { node = p; p = parent[node]; };
249 private int prev(int node) {
252 while(right[node] > 0) node = right[node];
255 int p = parent[node];
256 while(left[p] == node) { node = p; p = parent[node]; }
261 // Rotation and Balancing /////////////////////////////////////////////////////////////
270 // FIXME might be doing too much work here
271 private void rotate(boolean toTheLeft, int b, int p) {
272 int[] left = toTheLeft ? BalancedTree.left : BalancedTree.right;
273 int[] right = toTheLeft ? BalancedTree.right : BalancedTree.left;
276 if (d == 0) throw new Error("rotation error");
282 if(c != 0) parent[c] = b;
284 if (p == 0) root = d;
285 else if (left[p] == b) left[p] = d;
286 else if (right[p] == b) right[p] = d;
287 else throw new Error("rotate called with invalid parent");
288 size[b] = 1 + sizeof(left[b]) + sizeof(right[b]);
289 size[d] = 1 + sizeof(left[d]) + sizeof(right[d]);
292 private void balance(int slot, int p) {
293 if (slot <= 0) return;
294 size[slot] = 1 + sizeof(left[slot]) + sizeof(right[slot]);
295 if (sizeof(left[slot]) - 1 > 2 * sizeof(right[slot])) rotate(false, slot, p);
296 else if (sizeof(left[slot]) * 2 < sizeof(right[slot]) - 1) rotate(true, slot, p);
301 // Insert /////////////////////////////////////////////////////////////////////////
303 private void insert(int index, int arg, int slot, int p, boolean replace, boolean wentLeft) {
304 int diff = slot == 0 ? 0 : index - sizeof(left[slot]);
305 if (slot != 0 && diff != 0) {
306 if (diff < 0) insert(index, arg, left[slot], slot, replace, true);
307 else insert(index - sizeof(left[slot]) - 1, arg, right[slot], slot, replace, false);
312 if (size[arg] != 0) throw new Error("double insertion");
316 // we are replacing an existing node
318 if (diff != 0) throw new Error("this should never happen"); // since we already clamped the index
319 if (p == 0) root = arg;
320 else if (left[p] == slot) left[p] = arg;
321 else if (right[p] == slot) right[p] = arg;
322 else throw new Error("should never happen");
323 left[arg] = left[slot];
324 right[arg] = right[slot];
325 size[arg] = size[slot];
326 parent[arg] = parent[slot];
327 if(left[slot] != 0) parent[left[slot]] = arg;
328 if(right[slot] != 0) parent[right[slot]] = arg;
329 objects[slot] = null;
330 left[slot] = right[slot] = size[slot] = parent[slot] = 0;
333 // we become the child of a former leaf
334 } else if (slot == 0) {
335 int[] left = wentLeft ? BalancedTree.left : BalancedTree.right;
336 int[] right = wentLeft ? BalancedTree.right : BalancedTree.left;
337 // FEATURE: Might be doing too much work here
344 // we take the place of a preexisting node
347 left[arg] = left[slot]; // steal slot's left subtree
349 right[arg] = slot; // make slot our right subtree
350 parent[arg] = parent[slot];
352 if(left[arg] != 0) parent[left[arg]] = arg;
358 if (left[p] == slot) left[p] = arg;
359 else if (right[p] == slot) right[p] = arg;
360 else throw new Error("should never happen");
368 // Retrieval //////////////////////////////////////////////////////////////////////
370 private int get(int index, int slot) {
371 int diff = index - sizeof(left[slot]);
372 if (diff > 0) return get(diff - 1, right[slot]);
373 else if (diff < 0) return get(index, left[slot]);
378 // Deletion //////////////////////////////////////////////////////////////////////
380 private int delete(int index, int slot, int p) {
381 int diff = index - sizeof(left[slot]);
383 int ret = delete(index, left[slot], slot);
387 } else if (diff > 0) {
388 int ret = delete(diff - 1, right[slot], slot);
392 // we found the node to delete
395 // fast path: it has no children
396 if (left[slot] == 0 && right[slot] == 0) {
397 if (p == 0) root = 0;
399 int[] side = left[p] == slot ? left : right;
400 side[p] = side[slot]; // fix parent's pointer
403 // fast path: it has no left child, so we replace it with its right child
404 } else if (left[slot] == 0) {
405 if (p == 0) root = right[slot];
406 else (left[p] == slot ? left : right)[p] = right[slot]; // fix parent's pointer
407 parent[right[slot]] = p;
408 left[leftmost(right[slot])] = left[slot]; // fix our successor-leaf's fake right ptr
409 balance(right[slot], p);
411 // fast path; it has no right child, so we replace it with its left child
412 } else if (right[slot] == 0) {
413 if (p == 0) root = left[slot];
414 else (left[p] == slot ? left : right)[p] = left[slot]; // fix parent's pointer
415 parent[left[slot]] = p;
416 right[rightmost(left[slot])] = right[slot]; // fix our successor-leaf's fake right ptr
417 balance(left[slot], p);
419 // node to be deleted has two children, so we replace it with its left child's rightmost descendant
421 int left_childs_rightmost = delete(sizeof(left[slot]) - 1, left[slot], slot);
422 left[left_childs_rightmost] = left[slot];
423 right[left_childs_rightmost] = right[slot];
424 if(left[slot] != 0) parent[left[slot]] = left_childs_rightmost;
425 if(right[slot] != 0) parent[right[slot]] = left_childs_rightmost;
426 parent[left_childs_rightmost] = parent[slot];
427 if (p == 0) root = left_childs_rightmost;
428 else (left[p] == slot ? left : right)[p] = left_childs_rightmost; // fix parent's pointer
429 balance(left_childs_rightmost, p);
436 static class FinalizationHelper {
437 private BalancedTree bt;
438 FinalizationHelper(BalancedTree bt) { this.bt = bt; }
439 protected void finalize() { bt.clear(); }
442 // Debugging ///////////////////////////////////////////////////////////////////////////
444 public void check() { check(false); }
445 public void check(boolean expensive) {
446 if(expensive) System.err.println("--> Running expensive balanced tree checks");
449 for(int i=0;i<NUM_SLOTS;i++)
450 if(left[i] < 0 || right[i] < 0) throw new Error("someone inserted a negative number");
451 if(parent[root] != 0) throw new Error("parent of the root isn't 0");
452 if(left[0] != 0 || right[0] != 0 || size[0] != 0 || parent[0] != 0)
453 throw new Error("someone messed with [0]");
456 int n = leftmost(root);
457 while(n != 0) { c++; n = next(n); }
458 if(c != size[root]) throw new Error("size[] mismatch");
460 if(root != 0) check(root);
467 private void check(int node) {
468 //if(next(node) != next2(node)) throw new Error("next(" + node + ") != next2(" + node + ")");
469 //if(prev(node) != prev2(node)) throw new Error("prev(" + node + ") != prev2(" + node + ")");
472 if(parent[left[node]] != node) throw new Error("parent node mismatch on left child of " + node);
475 if(right[node] > 0) {
476 if(parent[right[node]] != node) throw new Error("parent node mismatch on right child of " + node);
481 public void printTree() {
482 if(root == 0) System.err.println("Tree is empty");
483 else printTree(root,0,false);
486 private void printTree(int node,int indent,boolean l) {
487 for(int i=0;i<indent;i++) System.err.print(" ");
488 if(node == 0) System.err.println("None");
490 System.err.print("" + node + ": " + objects[node]);
491 System.err.println(" Parent: " + parent[node] + " Size: " + size[node]);
492 printTree(left[node],indent+1,true);
493 printTree(right[node],indent+1,false);
497 public static void main(String[] args) {
498 BalancedTree t = new BalancedTree();
499 for(int i=0;i<args.length;i++)
500 t.insertNode(i,args[i]);
502 for(int n = t.leftmost(t.root); n != 0; n = t.next(n)) {
503 System.err.println("Next: " + n);
505 for(int n = t.rightmost(t.root); n != 0; n = t.prev(n)) {
506 System.err.println("Prev: " + n);
510 public void leafCheck() throws RuntimeException {
511 if (!validateLeaves()) {
514 throw new RuntimeException("bad tree: forward != back");
518 public boolean validateLeaves() {
519 int[] forward = getLeavesForward();
520 int[] backward = getLeavesBackward();
521 if (forward.length != backward.length) {
524 else if (forward.length > 0) {
525 for (int i = 0;i<forward.length;i++) {
526 if (forward[i] != backward[forward.length - i - 1]) {
534 public void printLeaves() {
535 System.out.println("");
536 int[] forward = getLeavesForward();
537 int[] backward = getLeavesBackward();
538 if (forward.length > 0) {
539 System.err.println("forward: " + backward.length);
540 for (int i = 0;i<forward.length;i++) {
541 System.err.println(forward[i]);
544 if (backward.length > 0) {
545 System.err.println("backward: " + backward.length);
546 for (int i = backward.length-1;i>=0;i--) {
547 System.err.println(backward[i]);
552 public int[] getLeavesForward() {
553 int[] leaves = new int[size[root]];
554 if (size[root] > 0) {
555 leaves[0] = leftmost(root);
556 for (int i=1;i < leaves.length;i++) {
557 leaves[i] = next(leaves[i-1]);
563 public int[] getLeavesBackward() {
564 int[] leaves = new int[size[root]];
565 if (size[root] > 0) {
566 leaves[0] = rightmost(root);
567 for (int i=1;i < leaves.length;i++) {
568 leaves[i] = prev(leaves[i-1]);
574 public void validateTree() {
575 if(root == 0) System.err.println("Tree is empty");
576 else validateTree(root,0,false);
577 System.err.println("");
579 private void validateTree(int node,int indent,boolean l) {
581 else if(node == 0) {}
583 System.err.println((l?"Prev: " : "Next: ") + -node);
584 validateTree(left[node],indent+1,true);
585 validateTree(right[node],indent+1,false);