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 // Public API //////////////////////////////////////////////////////////////////////////
30 /** the number of elements in the tree */
31 public final int treeSize() {
32 synchronized(BalancedTree.class) {
33 return root == 0 ? 0 : size[root];
37 /** clamps index to [0..treeSize()] and inserts object o *before* the specified index */
38 public final void insertNode(int index, Object o) {
39 synchronized(BalancedTree.class) {
40 if(o == null) throw new Error("can't insert nulls in the balanced tree");
41 cached_slot = cached_index = -1;
42 if (index < 0) index = 0;
43 if (index > treeSize()) index = treeSize();
44 int arg = allocateSlot(o);
46 insert(index, arg, root, 0, false, false);
49 left[arg] = right[arg] = parent[arg] = 0;
56 /** clamps index to [0..treeSize()-1] and replaces the object at that index with object o */
57 public final void replaceNode(int index, Object o) {
58 synchronized(BalancedTree.class) {
59 if(o == null) throw new Error("can't insert nulls in the balanced tree");
60 cached_slot = cached_index = -1;
61 if(root == 0) throw new Error("called replaceNode() on an empty tree");
62 if (index < 0) index = 0;
63 if (index >= treeSize()) index = treeSize() - 1;
64 int arg = allocateSlot(o);
65 insert(index, arg, root, 0, true, false);
70 /** returns the index of o; runs in O((log n)^2) time unless cache hit */
71 public final int indexNode(Object o) {
72 synchronized(BalancedTree.class) {
73 if(o == null) return -1;
74 if (cached_slot != -1 && objects[cached_slot] == o) return cached_index;
76 int slot = getSlot(o);
77 if(slot == -1) return -1;
81 // everything to the left is before us so add that to the index
82 index += sizeof(left[slot]);
83 // we are before anything on the right
84 while(left[parent[slot]] == slot) slot = parent[slot];
85 // we end of the first node who isn't on the left, go to the node that has as its child
87 // if we just processed the root we're done
89 // count the node we're currently on towards the index
96 /** returns the object at index; runs in O(log n) time unless cache hit */
97 public final Object getNode(int index) {
98 synchronized(BalancedTree.class) {
99 if (index == cached_index) return objects[cached_slot];
101 if (cached_index != -1) {
102 int distance = Math.abs(index - cached_index);
103 // if the in-order distance between the cached node and the
104 // target node is less than log(n), it's probably faster to
106 if ((distance < 16) && ((2 << distance) < treeSize())) {
107 while(cached_index > index) { cached_slot = prev(cached_slot); cached_index--; }
108 while(cached_index < index) { cached_slot = next(cached_slot); cached_index++; }
109 return objects[cached_slot];
113 cached_index = index;
114 cached_slot = get(index, root);
115 return objects[cached_slot];
117 return objects[get(index, root)];
121 /** deletes the object at index, returning the deleted object */
122 public final Object deleteNode(int index) {
123 synchronized(BalancedTree.class) {
124 cached_slot = cached_index = -1;
125 // FIXME: left[], right[], size[], and parent[] aren't getting cleared properly somewhere in here where a node had two children
126 int del = delete(index, root, 0);
127 left[del] = right[del] = size[del] = parent[del] = 0;
128 Object ret = objects[del];
135 public final void clear() {
136 synchronized(BalancedTree.class) {
137 if(root == 0) return;
138 int i = leftmost(root);
142 left[i] = right[i] = size[i] = parent[i] = 0;
150 // Node Data /////////////////////////////////////////////////////////////////////////
152 private final static int NUM_SLOTS = 64 * 1024;
153 // FEATURE: GROW - private final static int MAX_SLOT_DISTANCE = 32;
156 * Every object inserted into *any* tree gets a "slot" in this
157 * array. The slot is determined by hashcode modulo the length of
158 * the array, with quadradic probing to resolve collisions. NOTE
159 * that the "slot" of a node is NOT the same as its index.
160 * Furthermore, if an object is inserted into multiple trees, that
161 * object will have multiple slots.
163 private static Object[] objects = new Object[NUM_SLOTS];
165 /// These two arrays hold the left and right children of each
166 /// slot; in other words, left[x] is the *slot* of the left child
167 /// of the node in slot x.
169 /// If x has no left child, then left[x] is -1 multiplied by the
170 /// slot of the node that precedes x; if x is the first node, then
171 /// left[x] is 0. The right[] array works the same way.
173 private static int[] left = new int[NUM_SLOTS];
174 private static int[] right = new int[NUM_SLOTS];
176 /// The parent of this node (0 if it is the root node)
177 private static int[] parent = new int[NUM_SLOTS];
179 ///< the number of descendants of this node *including the node itself*
180 private static int[] size = new int[NUM_SLOTS];
183 // Slot Management //////////////////////////////////////////////////////////////////////
185 /** if alloc == false returns the slot holding object o. if alloc is true returns a new slot for obejct o */
186 private int getSlot(Object o, boolean alloc) {
187 // we XOR with our own hashcode so that we don't get tons of
188 // collisions when a single Object is inserted into multiple
190 int dest = Math.abs(o.hashCode() ^ this.hashCode()) % objects.length;
191 Object search = alloc ? null : o;
195 if(dest == 0) dest=1;
196 while (objects[dest] != search || !(alloc || root(dest) == root)) {
197 dest = Math.abs((odest + (plus ? 1 : -1) * tries * tries) % objects.length);
198 if (dest == 0) dest=1;
201 // FEATURE: GROW - if(tries > MAX_SLOT_DISTANCE) return -1;
206 /** returns the slots holding object o */
207 private int getSlot(Object o) { return getSlot(o,false); }
209 /** allocates a new slot holding object o*/
210 private int allocateSlot(Object o) {
211 int slot = getSlot(o, true);
212 // FEATURE: GROW - if(slot == -1) throw new Error("out of slots");
219 // Helpers /////////////////////////////////////////////////////////////////////////
221 // FEATURE: These might be faster if they aren't recursive
222 private final int leftmost(int slot) { return left[slot] <= 0 ? slot : leftmost(left[slot]); }
223 private final int rightmost(int slot) { return right[slot] <= 0 ? slot : rightmost(right[slot]); }
224 private final int sizeof(int slot) { return slot <= 0 ? 0 : size[slot]; }
225 private final int root(int slot) { return parent[slot] == 0 ? slot : root(parent[slot]); }
227 private int next(int node) {
228 if(right[node] > 0) {
230 while(left[node] > 0) node = left[node];
233 int p = parent[node];
234 while(right[p] == node) { node = p; p = parent[node]; };
239 private int prev(int node) {
242 while(right[node] > 0) node = right[node];
245 int p = parent[node];
246 while(left[p] == node) { node = p; p = parent[node]; }
251 // Rotation and Balancing /////////////////////////////////////////////////////////////
260 // FIXME might be doing too much work here
261 private void rotate(boolean toTheLeft, int b, int p) {
262 int[] left = toTheLeft ? BalancedTree.left : BalancedTree.right;
263 int[] right = toTheLeft ? BalancedTree.right : BalancedTree.left;
266 if (d == 0) throw new Error("rotation error");
272 if(c != 0) parent[c] = b;
274 if (p == 0) root = d;
275 else if (left[p] == b) left[p] = d;
276 else if (right[p] == b) right[p] = d;
277 else throw new Error("rotate called with invalid parent");
278 size[b] = 1 + sizeof(left[b]) + sizeof(right[b]);
279 size[d] = 1 + sizeof(left[d]) + sizeof(right[d]);
282 private void balance(int slot, int p) {
283 if (slot <= 0) return;
284 size[slot] = 1 + sizeof(left[slot]) + sizeof(right[slot]);
285 if (sizeof(left[slot]) - 1 > 2 * sizeof(right[slot])) rotate(false, slot, p);
286 else if (sizeof(left[slot]) * 2 < sizeof(right[slot]) - 1) rotate(true, slot, p);
291 // Insert /////////////////////////////////////////////////////////////////////////
293 private void insert(int index, int arg, int slot, int p, boolean replace, boolean wentLeft) {
294 int diff = slot == 0 ? 0 : index - sizeof(left[slot]);
295 if (slot != 0 && diff != 0) {
296 if (diff < 0) insert(index, arg, left[slot], slot, replace, true);
297 else insert(index - sizeof(left[slot]) - 1, arg, right[slot], slot, replace, false);
302 if (size[arg] != 0) throw new Error("double insertion");
306 // we are replacing an existing node
308 if (diff != 0) throw new Error("this should never happen"); // since we already clamped the index
309 if (p == 0) root = arg;
310 else if (left[p] == slot) left[p] = arg;
311 else if (right[p] == slot) right[p] = arg;
312 else throw new Error("should never happen");
313 left[arg] = left[slot];
314 right[arg] = right[slot];
315 size[arg] = size[slot];
316 parent[arg] = parent[slot];
317 if(left[slot] != 0) parent[left[slot]] = arg;
318 if(right[slot] != 0) parent[right[slot]] = arg;
319 objects[slot] = null;
320 left[slot] = right[slot] = size[slot] = parent[slot] = 0;
323 // we become the child of a former leaf
324 } else if (slot == 0) {
325 int[] left = wentLeft ? BalancedTree.left : BalancedTree.right;
326 int[] right = wentLeft ? BalancedTree.right : BalancedTree.left;
327 // FEATURE: Might be doing too much work here
334 // we take the place of a preexisting node
337 left[arg] = left[slot]; // steal slot's left subtree
339 right[arg] = slot; // make slot our right subtree
340 parent[arg] = parent[slot];
342 if(left[arg] != 0) parent[left[arg]] = arg;
348 if (left[p] == slot) left[p] = arg;
349 else if (right[p] == slot) right[p] = arg;
350 else throw new Error("should never happen");
358 // Retrieval //////////////////////////////////////////////////////////////////////
360 private int get(int index, int slot) {
361 int diff = index - sizeof(left[slot]);
362 if (diff > 0) return get(diff - 1, right[slot]);
363 else if (diff < 0) return get(index, left[slot]);
368 // Deletion //////////////////////////////////////////////////////////////////////
370 private int delete(int index, int slot, int p) {
371 int diff = index - sizeof(left[slot]);
373 int ret = delete(index, left[slot], slot);
377 } else if (diff > 0) {
378 int ret = delete(diff - 1, right[slot], slot);
382 // we found the node to delete
385 // fast path: it has no children
386 if (left[slot] == 0 && right[slot] == 0) {
387 if (p == 0) root = 0;
389 int[] side = left[p] == slot ? left : right;
390 side[p] = side[slot]; // fix parent's pointer
393 // fast path: it has no left child, so we replace it with its right child
394 } else if (left[slot] == 0) {
395 if (p == 0) root = right[slot];
396 else (left[p] == slot ? left : right)[p] = right[slot]; // fix parent's pointer
397 parent[right[slot]] = p;
398 left[leftmost(right[slot])] = left[slot]; // fix our successor-leaf's fake right ptr
399 balance(right[slot], p);
401 // fast path; it has no right child, so we replace it with its left child
402 } else if (right[slot] == 0) {
403 if (p == 0) root = left[slot];
404 else (left[p] == slot ? left : right)[p] = left[slot]; // fix parent's pointer
405 parent[left[slot]] = p;
406 right[rightmost(left[slot])] = right[slot]; // fix our successor-leaf's fake right ptr
407 balance(left[slot], p);
409 // node to be deleted has two children, so we replace it with its left child's rightmost descendant
411 int left_childs_rightmost = delete(sizeof(left[slot]) - 1, left[slot], slot);
412 left[left_childs_rightmost] = left[slot];
413 right[left_childs_rightmost] = right[slot];
414 if(left[slot] != 0) parent[left[slot]] = left_childs_rightmost;
415 if(right[slot] != 0) parent[right[slot]] = left_childs_rightmost;
416 parent[left_childs_rightmost] = parent[slot];
417 if (p == 0) root = left_childs_rightmost;
418 else (left[p] == slot ? left : right)[p] = left_childs_rightmost; // fix parent's pointer
419 balance(left_childs_rightmost, p);
426 protected void finalize() { clear(); }
428 // Debugging ///////////////////////////////////////////////////////////////////////////
430 public void check() { check(false); }
431 public void check(boolean expensive) {
432 if(expensive) System.err.println("--> Running expensive balanced tree checks");
435 for(int i=0;i<NUM_SLOTS;i++)
436 if(left[i] < 0 || right[i] < 0) throw new Error("someone inserted a negative number");
437 if(parent[root] != 0) throw new Error("parent of the root isn't 0");
438 if(left[0] != 0 || right[0] != 0 || size[0] != 0 || parent[0] != 0)
439 throw new Error("someone messed with [0]");
442 int n = leftmost(root);
443 while(n != 0) { c++; n = next(n); }
444 if(c != size[root]) throw new Error("size[] mismatch");
446 if(root != 0) check(root);
453 private void check(int node) {
454 //if(next(node) != next2(node)) throw new Error("next(" + node + ") != next2(" + node + ")");
455 //if(prev(node) != prev2(node)) throw new Error("prev(" + node + ") != prev2(" + node + ")");
458 if(parent[left[node]] != node) throw new Error("parent node mismatch on left child of " + node);
461 if(right[node] > 0) {
462 if(parent[right[node]] != node) throw new Error("parent node mismatch on right child of " + node);
467 public void printTree() {
468 if(root == 0) System.err.println("Tree is empty");
469 else printTree(root,0,false);
472 private void printTree(int node,int indent,boolean l) {
473 for(int i=0;i<indent;i++) System.err.print(" ");
474 if(node == 0) System.err.println("None");
476 System.err.print("" + node + ": " + objects[node]);
477 System.err.println(" Parent: " + parent[node] + " Size: " + size[node]);
478 printTree(left[node],indent+1,true);
479 printTree(right[node],indent+1,false);
483 /*public static void main(String[] args) {
484 BalancedTree t = new BalancedTree();
485 for(int i=0;i<args.length;i++)
486 t.insertNode(i,args[i]);
488 for(int n = t.leftmost(t.root); n != 0; n = t.next(n)) {
489 System.err.println("Next: " + n);
491 for(int n = t.rightmost(t.root); n != 0; n = t.prev(n)) {
492 System.err.println("Prev: " + n);