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(o == null) throw new Error("can't insert nulls in the balanced tree");
43 cached_slot = cached_index = -1;
44 if (index < 0) index = 0;
45 if (index > treeSize()) index = treeSize();
46 int arg = allocateSlot(o);
48 insert(index, arg, root, 0, false, false);
50 if(fh == null) fh = new FinalizationHelper(this);
52 left[arg] = right[arg] = parent[arg] = 0;
59 /** clamps index to [0..treeSize()-1] and replaces the object at that index with object o */
60 public final void replaceNode(int index, Object o) {
61 synchronized(BalancedTree.class) {
62 if(o == null) throw new Error("can't insert nulls in the balanced tree");
63 cached_slot = cached_index = -1;
64 if(root == 0) throw new Error("called replaceNode() on an empty tree");
65 if (index < 0) index = 0;
66 if (index >= treeSize()) index = treeSize() - 1;
67 int arg = allocateSlot(o);
68 insert(index, arg, root, 0, true, false);
73 /** returns the index of o; runs in O((log n)^2) time unless cache hit */
74 public final int indexNode(Object o) {
75 synchronized(BalancedTree.class) {
76 if(o == null) return -1;
77 if (cached_slot != -1 && objects[cached_slot] == o) return cached_index;
79 int slot = getSlot(o);
80 if(slot == -1) return -1;
84 // everything to the left is before us so add that to the index
85 index += sizeof(left[slot]);
86 // we are before anything on the right
87 while(left[parent[slot]] == slot) slot = parent[slot];
88 // we end of the first node who isn't on the left, go to the node that has as its child
90 // if we just processed the root we're done
92 // count the node we're currently on towards the index
99 /** returns the object at index; runs in O(log n) time unless cache hit */
100 public final Object getNode(int index) {
101 synchronized(BalancedTree.class) {
102 if (index == cached_index) return objects[cached_slot];
104 if (cached_index != -1) {
105 int distance = Math.abs(index - cached_index);
106 // if the in-order distance between the cached node and the
107 // target node is less than log(n), it's probably faster to
109 if ((distance < 16) && ((2 << distance) < treeSize())) {
110 while(cached_index > index) { cached_slot = prev(cached_slot); cached_index--; }
111 while(cached_index < index) { cached_slot = next(cached_slot); cached_index++; }
112 return objects[cached_slot];
116 cached_index = index;
117 cached_slot = get(index, root);
118 return objects[cached_slot];
120 return objects[get(index, root)];
124 /** deletes the object at index, returning the deleted object */
125 public final Object deleteNode(int index) {
126 synchronized(BalancedTree.class) {
127 cached_slot = cached_index = -1;
128 // FIXME: left[], right[], size[], and parent[] aren't getting cleared properly somewhere in here where a node had two children
129 int del = delete(index, root, 0);
130 left[del] = right[del] = size[del] = parent[del] = 0;
131 Object ret = objects[del];
138 public final void clear() {
139 synchronized(BalancedTree.class) {
140 if(root == 0) return;
141 int i = leftmost(root);
145 left[i] = right[i] = size[i] = parent[i] = 0;
153 // Node Data /////////////////////////////////////////////////////////////////////////
155 private final static int NUM_SLOTS = 64 * 1024;
156 // FEATURE: GROW - private final static int MAX_SLOT_DISTANCE = 32;
159 * Every object inserted into *any* tree gets a "slot" in this
160 * array. The slot is determined by hashcode modulo the length of
161 * the array, with quadradic probing to resolve collisions. NOTE
162 * that the "slot" of a node is NOT the same as its index.
163 * Furthermore, if an object is inserted into multiple trees, that
164 * object will have multiple slots.
166 private static Object[] objects = new Object[NUM_SLOTS];
168 /// These two arrays hold the left and right children of each
169 /// slot; in other words, left[x] is the *slot* of the left child
170 /// of the node in slot x.
172 /// If x has no left child, then left[x] is -1 multiplied by the
173 /// slot of the node that precedes x; if x is the first node, then
174 /// left[x] is 0. The right[] array works the same way.
176 private static int[] left = new int[NUM_SLOTS];
177 private static int[] right = new int[NUM_SLOTS];
179 /// The parent of this node (0 if it is the root node)
180 private static int[] parent = new int[NUM_SLOTS];
182 ///< the number of descendants of this node *including the node itself*
183 private static int[] size = new int[NUM_SLOTS];
186 // Slot Management //////////////////////////////////////////////////////////////////////
188 /** if alloc == false returns the slot holding object o. if alloc is true returns a new slot for obejct o */
189 private int getSlot(Object o, boolean alloc) {
190 // we XOR with our own hashcode so that we don't get tons of
191 // collisions when a single Object is inserted into multiple
193 int dest = Math.abs(o.hashCode() ^ this.hashCode()) % objects.length;
194 Object search = alloc ? null : o;
198 if(dest == 0) dest=1;
199 while (objects[dest] != search || !(alloc || root(dest) == root)) {
200 dest = Math.abs((odest + (plus ? 1 : -1) * tries * tries) % objects.length);
201 if (dest == 0) dest=1;
204 // FEATURE: GROW - if(tries > MAX_SLOT_DISTANCE) return -1;
209 /** returns the slots holding object o */
210 private int getSlot(Object o) { return getSlot(o,false); }
212 /** allocates a new slot holding object o*/
213 private int allocateSlot(Object o) {
214 int slot = getSlot(o, true);
215 // FEATURE: GROW - if(slot == -1) throw new Error("out of slots");
222 // Helpers /////////////////////////////////////////////////////////////////////////
224 // FEATURE: These might be faster if they aren't recursive
225 private final int leftmost(int slot) { return left[slot] <= 0 ? slot : leftmost(left[slot]); }
226 private final int rightmost(int slot) { return right[slot] <= 0 ? slot : rightmost(right[slot]); }
227 private final int sizeof(int slot) { return slot <= 0 ? 0 : size[slot]; }
228 private final int root(int slot) { return parent[slot] == 0 ? slot : root(parent[slot]); }
230 private int next(int node) {
231 if(right[node] > 0) {
233 while(left[node] > 0) node = left[node];
236 int p = parent[node];
237 while(right[p] == node) { node = p; p = parent[node]; };
242 private int prev(int node) {
245 while(right[node] > 0) node = right[node];
248 int p = parent[node];
249 while(left[p] == node) { node = p; p = parent[node]; }
254 // Rotation and Balancing /////////////////////////////////////////////////////////////
263 // FIXME might be doing too much work here
264 private void rotate(boolean toTheLeft, int b, int p) {
265 int[] left = toTheLeft ? BalancedTree.left : BalancedTree.right;
266 int[] right = toTheLeft ? BalancedTree.right : BalancedTree.left;
269 if (d == 0) throw new Error("rotation error");
275 if(c != 0) parent[c] = b;
277 if (p == 0) root = d;
278 else if (left[p] == b) left[p] = d;
279 else if (right[p] == b) right[p] = d;
280 else throw new Error("rotate called with invalid parent");
281 size[b] = 1 + sizeof(left[b]) + sizeof(right[b]);
282 size[d] = 1 + sizeof(left[d]) + sizeof(right[d]);
285 private void balance(int slot, int p) {
286 if (slot <= 0) return;
287 size[slot] = 1 + sizeof(left[slot]) + sizeof(right[slot]);
288 if (sizeof(left[slot]) - 1 > 2 * sizeof(right[slot])) rotate(false, slot, p);
289 else if (sizeof(left[slot]) * 2 < sizeof(right[slot]) - 1) rotate(true, slot, p);
294 // Insert /////////////////////////////////////////////////////////////////////////
296 private void insert(int index, int arg, int slot, int p, boolean replace, boolean wentLeft) {
297 int diff = slot == 0 ? 0 : index - sizeof(left[slot]);
298 if (slot != 0 && diff != 0) {
299 if (diff < 0) insert(index, arg, left[slot], slot, replace, true);
300 else insert(index - sizeof(left[slot]) - 1, arg, right[slot], slot, replace, false);
305 if (size[arg] != 0) throw new Error("double insertion");
309 // we are replacing an existing node
311 if (diff != 0) throw new Error("this should never happen"); // since we already clamped the index
312 if (p == 0) root = arg;
313 else if (left[p] == slot) left[p] = arg;
314 else if (right[p] == slot) right[p] = arg;
315 else throw new Error("should never happen");
316 left[arg] = left[slot];
317 right[arg] = right[slot];
318 size[arg] = size[slot];
319 parent[arg] = parent[slot];
320 if(left[slot] != 0) parent[left[slot]] = arg;
321 if(right[slot] != 0) parent[right[slot]] = arg;
322 objects[slot] = null;
323 left[slot] = right[slot] = size[slot] = parent[slot] = 0;
326 // we become the child of a former leaf
327 } else if (slot == 0) {
328 int[] left = wentLeft ? BalancedTree.left : BalancedTree.right;
329 int[] right = wentLeft ? BalancedTree.right : BalancedTree.left;
330 // FEATURE: Might be doing too much work here
337 // we take the place of a preexisting node
340 left[arg] = left[slot]; // steal slot's left subtree
342 right[arg] = slot; // make slot our right subtree
343 parent[arg] = parent[slot];
345 if(left[arg] != 0) parent[left[arg]] = arg;
351 if (left[p] == slot) left[p] = arg;
352 else if (right[p] == slot) right[p] = arg;
353 else throw new Error("should never happen");
361 // Retrieval //////////////////////////////////////////////////////////////////////
363 private int get(int index, int slot) {
364 int diff = index - sizeof(left[slot]);
365 if (diff > 0) return get(diff - 1, right[slot]);
366 else if (diff < 0) return get(index, left[slot]);
371 // Deletion //////////////////////////////////////////////////////////////////////
373 private int delete(int index, int slot, int p) {
374 int diff = index - sizeof(left[slot]);
376 int ret = delete(index, left[slot], slot);
380 } else if (diff > 0) {
381 int ret = delete(diff - 1, right[slot], slot);
385 // we found the node to delete
388 // fast path: it has no children
389 if (left[slot] == 0 && right[slot] == 0) {
390 if (p == 0) root = 0;
392 int[] side = left[p] == slot ? left : right;
393 side[p] = side[slot]; // fix parent's pointer
396 // fast path: it has no left child, so we replace it with its right child
397 } else if (left[slot] == 0) {
398 if (p == 0) root = right[slot];
399 else (left[p] == slot ? left : right)[p] = right[slot]; // fix parent's pointer
400 parent[right[slot]] = p;
401 left[leftmost(right[slot])] = left[slot]; // fix our successor-leaf's fake right ptr
402 balance(right[slot], p);
404 // fast path; it has no right child, so we replace it with its left child
405 } else if (right[slot] == 0) {
406 if (p == 0) root = left[slot];
407 else (left[p] == slot ? left : right)[p] = left[slot]; // fix parent's pointer
408 parent[left[slot]] = p;
409 right[rightmost(left[slot])] = right[slot]; // fix our successor-leaf's fake right ptr
410 balance(left[slot], p);
412 // node to be deleted has two children, so we replace it with its left child's rightmost descendant
414 int left_childs_rightmost = delete(sizeof(left[slot]) - 1, left[slot], slot);
415 left[left_childs_rightmost] = left[slot];
416 right[left_childs_rightmost] = right[slot];
417 if(left[slot] != 0) parent[left[slot]] = left_childs_rightmost;
418 if(right[slot] != 0) parent[right[slot]] = left_childs_rightmost;
419 parent[left_childs_rightmost] = parent[slot];
420 if (p == 0) root = left_childs_rightmost;
421 else (left[p] == slot ? left : right)[p] = left_childs_rightmost; // fix parent's pointer
422 balance(left_childs_rightmost, p);
429 static class FinalizationHelper {
430 private BalancedTree bt;
431 FinalizationHelper(BalancedTree bt) { this.bt = bt; }
432 protected void finalize() { bt.clear(); }
435 // Debugging ///////////////////////////////////////////////////////////////////////////
437 public void check() { check(false); }
438 public void check(boolean expensive) {
439 if(expensive) System.err.println("--> Running expensive balanced tree checks");
442 for(int i=0;i<NUM_SLOTS;i++)
443 if(left[i] < 0 || right[i] < 0) throw new Error("someone inserted a negative number");
444 if(parent[root] != 0) throw new Error("parent of the root isn't 0");
445 if(left[0] != 0 || right[0] != 0 || size[0] != 0 || parent[0] != 0)
446 throw new Error("someone messed with [0]");
449 int n = leftmost(root);
450 while(n != 0) { c++; n = next(n); }
451 if(c != size[root]) throw new Error("size[] mismatch");
453 if(root != 0) check(root);
460 private void check(int node) {
461 //if(next(node) != next2(node)) throw new Error("next(" + node + ") != next2(" + node + ")");
462 //if(prev(node) != prev2(node)) throw new Error("prev(" + node + ") != prev2(" + node + ")");
465 if(parent[left[node]] != node) throw new Error("parent node mismatch on left child of " + node);
468 if(right[node] > 0) {
469 if(parent[right[node]] != node) throw new Error("parent node mismatch on right child of " + node);
474 public void printTree() {
475 if(root == 0) System.err.println("Tree is empty");
476 else printTree(root,0,false);
479 private void printTree(int node,int indent,boolean l) {
480 for(int i=0;i<indent;i++) System.err.print(" ");
481 if(node == 0) System.err.println("None");
483 System.err.print("" + node + ": " + objects[node]);
484 System.err.println(" Parent: " + parent[node] + " Size: " + size[node]);
485 printTree(left[node],indent+1,true);
486 printTree(right[node],indent+1,false);
490 public static void main(String[] args) {
491 BalancedTree t = new BalancedTree();
492 for(int i=0;i<args.length;i++)
493 t.insertNode(i,args[i]);
495 for(int n = t.leftmost(t.root); n != 0; n = t.next(n)) {
496 System.err.println("Next: " + n);
498 for(int n = t.rightmost(t.root); n != 0; n = t.prev(n)) {
499 System.err.println("Prev: " + n);