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");
276 if(c != 0) parent[c] = b;
278 if (p == 0) root = d;
279 else if (left[p] == b) left[p] = d;
280 else if (right[p] == b) right[p] = d;
281 else throw new Error("rotate called with invalid parent");
282 size[b] = 1 + sizeof(left[b]) + sizeof(right[b]);
283 size[d] = 1 + sizeof(left[d]) + sizeof(right[d]);
285 if(DEBUG) try { check(); } catch(Error e) { System.err.println("rotate: " + toTheLeft + "," + b + "," + p); throw e; }
288 private void balance(int slot, int p) {
289 if (slot <= 0) return;
290 size[slot] = 1 + sizeof(left[slot]) + sizeof(right[slot]);
291 if (sizeof(left[slot]) - 1 > 2 * sizeof(right[slot])) rotate(false, slot, p);
292 else if (sizeof(left[slot]) * 2 < sizeof(right[slot]) - 1) rotate(true, slot, p);
297 // Insert /////////////////////////////////////////////////////////////////////////
299 private void insert(int index, int arg, int slot, int p, boolean replace, boolean wentLeft) {
300 int diff = slot == 0 ? 0 : index - sizeof(left[slot]);
301 if (slot != 0 && diff != 0) {
302 if (diff < 0) insert(index, arg, left[slot], slot, replace, true);
303 else insert(index - sizeof(left[slot]) - 1, arg, right[slot], slot, replace, false);
308 if (size[arg] != 0) throw new Error("double insertion");
312 // we are replacing an existing node
314 if (diff != 0) throw new Error("this should never happen"); // since we already clamped the index
315 if (p == 0) root = arg;
316 else if (left[p] == slot) left[p] = arg;
317 else if (right[p] == slot) right[p] = arg;
318 else throw new Error("should never happen");
319 left[arg] = left[slot];
320 right[arg] = right[slot];
321 size[arg] = size[slot];
322 parent[arg] = parent[slot];
323 if(left[slot] != 0) parent[left[slot]] = arg;
324 if(right[slot] != 0) parent[right[slot]] = arg;
325 objects[slot] = null;
326 left[slot] = right[slot] = size[slot] = parent[slot] = 0;
329 // we become the child of a former leaf
330 } else if (slot == 0) {
331 int[] left = wentLeft ? BalancedTree.left : BalancedTree.right;
332 int[] right = wentLeft ? BalancedTree.right : BalancedTree.left;
333 // FEATURE: Might be doing too much work here
341 // we take the place of a preexisting node
344 left[arg] = left[slot]; // steal slot's left subtree
346 right[arg] = slot; // make slot our right subtree
347 parent[arg] = parent[slot];
349 if(left[arg] != 0) parent[left[arg]] = arg;
356 if (left[p] == slot) left[p] = arg;
357 else if (right[p] == slot) right[p] = arg;
358 else throw new Error("should never happen");
367 // Retrieval //////////////////////////////////////////////////////////////////////
369 private int get(int index, int slot) {
370 int diff = index - sizeof(left[slot]);
371 if (diff > 0) return get(diff - 1, right[slot]);
372 else if (diff < 0) return get(index, left[slot]);
377 // Deletion //////////////////////////////////////////////////////////////////////
379 private int delete(int index, int slot, int p) {
380 int diff = index - sizeof(left[slot]);
382 int ret = delete(index, left[slot], slot);
386 } else if (diff > 0) {
387 int ret = delete(diff - 1, right[slot], slot);
391 // we found the node to delete
394 // fast path: it has no children
395 if (left[slot] == 0 && right[slot] == 0) {
396 if (p == 0) root = 0;
398 int[] side = left[p] == slot ? left : right;
399 side[p] = side[slot]; // fix parent's pointer
402 // fast path: it has no left child, so we replace it with its right child
403 } else if (left[slot] == 0) {
404 if (p == 0) root = right[slot];
405 else (left[p] == slot ? left : right)[p] = right[slot]; // fix parent's pointer
406 parent[right[slot]] = p;
407 left[leftmost(right[slot])] = left[slot]; // fix our successor-leaf's fake right ptr
408 balance(right[slot], p);
410 // fast path; it has no right child, so we replace it with its left child
411 } else if (right[slot] == 0) {
412 if (p == 0) root = left[slot];
413 else (left[p] == slot ? left : right)[p] = left[slot]; // fix parent's pointer
414 parent[left[slot]] = p;
415 right[rightmost(left[slot])] = right[slot]; // fix our successor-leaf's fake right ptr
416 balance(left[slot], p);
418 // node to be deleted has two children, so we replace it with its left child's rightmost descendant
420 int left_childs_rightmost = delete(sizeof(left[slot]) - 1, left[slot], slot);
421 left[left_childs_rightmost] = left[slot];
422 right[left_childs_rightmost] = right[slot];
423 if(left[slot] != 0) parent[left[slot]] = left_childs_rightmost;
424 if(right[slot] != 0) parent[right[slot]] = left_childs_rightmost;
425 parent[left_childs_rightmost] = parent[slot];
426 if (p == 0) root = left_childs_rightmost;
427 else (left[p] == slot ? left : right)[p] = left_childs_rightmost; // fix parent's pointer
428 balance(left_childs_rightmost, p);
435 static class FinalizationHelper {
436 private BalancedTree bt;
437 FinalizationHelper(BalancedTree bt) { this.bt = bt; }
438 protected void finalize() { bt.clear(); }
441 // Debugging ///////////////////////////////////////////////////////////////////////////
443 public void check() { check(false); }
444 public void check(boolean expensive) {
445 if(expensive) System.err.println("--> Running expensive balanced tree checks");
448 for(int i=0;i<NUM_SLOTS;i++)
449 if(left[i] < 0 || right[i] < 0) throw new Error("someone inserted a negative number");
450 if(parent[root] != 0) throw new Error("parent of the root isn't 0");
451 if(left[0] != 0 || right[0] != 0 || size[0] != 0 || parent[0] != 0)
452 throw new Error("someone messed with [0]");
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]);
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);