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 // Instance Variables ///////////////////////////////////////////////////////////////////
21 private int root = 0; ///< the slot of the root element
23 private int cached_index = -1;
24 private int cached_slot = -1;
26 // Public API //////////////////////////////////////////////////////////////////////////
28 /** the number of elements in the tree */
29 public final int treeSize() {
30 synchronized(BalancedTree.class) {
31 return root == 0 ? 0 : size[root];
35 /** clamps index to [0..treeSize()] and inserts object o *before* the specified index */
36 public final void insertNode(int index, Object o) {
37 synchronized(BalancedTree.class) {
38 if(o == null) throw new Error("can't insert nulls in the balanced tree");
39 cached_slot = cached_index = -1;
40 if (index < 0) index = 0;
41 if (index > treeSize()) index = treeSize();
42 int arg = allocateSlot(o);
44 insert(index, arg, root, 0, false, false);
47 left[arg] = right[arg] = parent[arg] = 0;
53 /** clamps index to [0..treeSize()-1] and replaces the object at that index with object o */
54 public final void replaceNode(int index, Object o) {
55 synchronized(BalancedTree.class) {
56 if(o == null) throw new Error("can't insert nulls in the balanced tree");
57 cached_slot = cached_index = -1;
58 if(root == 0) throw new Error("called replaceNode() on an empty tree");
59 if (index < 0) index = 0;
60 if (index >= treeSize()) index = treeSize() - 1;
61 int arg = allocateSlot(o);
62 insert(index, arg, root, 0, true, false);
66 /** returns the index of o; runs in O((log n)^2) time unless cache hit */
67 public final int indexNode(Object o) {
68 synchronized(BalancedTree.class) {
69 if(o == null) return -1;
70 if (cached_slot != -1 && objects[cached_slot] == o) return cached_index;
72 int slot = getSlot(o);
73 if(slot == -1) return -1;
77 // everything to the left is before us so add that to the index
78 index += sizeof(left[slot]);
79 // we are before anything on the right
80 while(left[parent[slot]] == slot) slot = parent[slot];
81 // we end of the first node who isn't on the left, go to the node that has as its child
83 // if we just processed the root we're done
85 // count the node we're currently on towards the index
92 /** returns the object at index; runs in O(log n) time unless cache hit */
93 public final Object getNode(int index) {
94 synchronized(BalancedTree.class) {
95 if (index == cached_index) return objects[cached_slot];
97 if (cached_index != -1) {
98 int distance = Math.abs(index - cached_index);
99 // if the in-order distance between the cached node and the
100 // target node is less than log(n), it's probably faster to
102 if ((distance < 16) && ((2 << distance) < treeSize())) {
103 while(cached_index > index) { cached_slot = prev(cached_slot); cached_index--; }
104 while(cached_index < index) { cached_slot = next(cached_slot); cached_index++; }
105 return objects[cached_slot];
109 cached_index = index;
110 cached_slot = get(index, root);
111 return objects[cached_slot];
113 return objects[get(index, root)];
117 /** deletes the object at index, returning the deleted object */
118 public final Object deleteNode(int index) {
119 synchronized(BalancedTree.class) {
120 cached_slot = cached_index = -1;
121 // FIXME: left[], right[], size[], and parent[] aren't getting cleared properly somewhere in here where a node had two children
122 int del = delete(index, root, 0);
123 left[del] = right[del] = size[del] = parent[del] = 0;
124 Object ret = objects[del];
130 public final void clear() {
131 synchronized(BalancedTree.class) {
132 if(root == 0) return;
133 int i = leftmost(root);
137 left[i] = right[i] = size[i] = parent[i] = 0;
144 // Node Data /////////////////////////////////////////////////////////////////////////
146 private final static int NUM_SLOTS = 64 * 1024;
147 // FEATURE: GROW - private final static int MAX_SLOT_DISTANCE = 32;
150 * Every object inserted into *any* tree gets a "slot" in this
151 * array. The slot is determined by hashcode modulo the length of
152 * the array, with quadradic probing to resolve collisions. NOTE
153 * that the "slot" of a node is NOT the same as its index.
154 * Furthermore, if an object is inserted into multiple trees, that
155 * object will have multiple slots.
157 private static Object[] objects = new Object[NUM_SLOTS];
159 /// These two arrays hold the left and right children of each
160 /// slot; in other words, left[x] is the *slot* of the left child
161 /// of the node in slot x.
163 /// If x has no left child, then left[x] is -1 multiplied by the
164 /// slot of the node that precedes x; if x is the first node, then
165 /// left[x] is 0. The right[] array works the same way.
167 private static int[] left = new int[NUM_SLOTS];
168 private static int[] right = new int[NUM_SLOTS];
170 /// The parent of this node (0 if it is the root node)
171 private static int[] parent = new int[NUM_SLOTS];
173 ///< the number of descendants of this node *including the node itself*
174 private static int[] size = new int[NUM_SLOTS];
177 // Slot Management //////////////////////////////////////////////////////////////////////
179 /** if alloc == false returns the slot holding object o. if alloc is true returns a new slot for obejct o */
180 private int getSlot(Object o, boolean alloc) {
181 // we XOR with our own hashcode so that we don't get tons of
182 // collisions when a single Object is inserted into multiple
184 int dest = Math.abs(o.hashCode() ^ this.hashCode()) % objects.length;
185 Object search = alloc ? null : o;
189 if(dest == 0) dest=1;
190 while (objects[dest] != search || !(alloc || root(dest) == root)) {
191 dest = Math.abs((odest + (plus ? 1 : -1) * tries * tries) % objects.length);
192 if (dest == 0) dest=1;
195 // FEATURE: GROW - if(tries > MAX_SLOT_DISTANCE) return -1;
200 /** returns the slots holding object o */
201 private int getSlot(Object o) { return getSlot(o,false); }
203 /** allocates a new slot holding object o*/
204 private int allocateSlot(Object o) {
205 int slot = getSlot(o, true);
206 // FEATURE: GROW - if(slot == -1) throw new Error("out of slots");
213 // Helpers /////////////////////////////////////////////////////////////////////////
215 // FEATURE: These might be faster if they aren't recursive
216 private final int leftmost(int slot) { return left[slot] <= 0 ? slot : leftmost(left[slot]); }
217 private final int rightmost(int slot) { return right[slot] <= 0 ? slot : rightmost(right[slot]); }
218 private final int sizeof(int slot) { return slot <= 0 ? 0 : size[slot]; }
219 private final int root(int slot) { return parent[slot] == 0 ? slot : root(parent[slot]); }
221 private int next(int node) {
222 if(right[node] > 0) {
224 while(left[node] > 0) node = left[node];
227 int p = parent[node];
228 while(right[p] == node) { node = p; p = parent[node]; };
233 private int prev(int node) {
236 while(right[node] > 0) node = right[node];
239 int p = parent[node];
240 while(left[p] == node) { node = p; p = parent[node]; }
245 // Rotation and Balancing /////////////////////////////////////////////////////////////
254 // FIXME might be doing too much work here
255 private void rotate(boolean toTheLeft, int b, int p) {
256 int[] left = toTheLeft ? BalancedTree.left : BalancedTree.right;
257 int[] right = toTheLeft ? BalancedTree.right : BalancedTree.left;
260 if (d == 0) throw new Error("rotation error");
266 if(c != 0) parent[c] = b;
268 if (p == 0) root = d;
269 else if (left[p] == b) left[p] = d;
270 else if (right[p] == b) right[p] = d;
271 else throw new Error("rotate called with invalid parent");
272 size[b] = 1 + sizeof(left[b]) + sizeof(right[b]);
273 size[d] = 1 + sizeof(left[d]) + sizeof(right[d]);
276 private void balance(int slot, int p) {
277 if (slot <= 0) return;
278 size[slot] = 1 + sizeof(left[slot]) + sizeof(right[slot]);
279 if (sizeof(left[slot]) - 1 > 2 * sizeof(right[slot])) rotate(false, slot, p);
280 else if (sizeof(left[slot]) * 2 < sizeof(right[slot]) - 1) rotate(true, slot, p);
285 // Insert /////////////////////////////////////////////////////////////////////////
287 private void insert(int index, int arg, int slot, int p, boolean replace, boolean wentLeft) {
288 int diff = slot == 0 ? 0 : index - sizeof(left[slot]);
289 if (slot != 0 && diff != 0) {
290 if (diff < 0) insert(index, arg, left[slot], slot, replace, true);
291 else insert(index - sizeof(left[slot]) - 1, arg, right[slot], slot, replace, false);
296 if (size[arg] != 0) throw new Error("double insertion");
298 // we are replacing an existing node
300 if (diff != 0) throw new Error("this should never happen"); // since we already clamped the index
301 if (p == 0) root = arg;
302 else if (left[p] == slot) left[p] = arg;
303 else if (right[p] == slot) right[p] = arg;
304 else throw new Error("should never happen");
305 left[arg] = left[slot];
306 right[arg] = right[slot];
307 size[arg] = size[slot];
308 parent[arg] = parent[slot];
309 if(left[slot] != 0) parent[left[slot]] = arg;
310 if(right[slot] != 0) parent[right[slot]] = arg;
311 objects[slot] = null;
312 left[slot] = right[slot] = size[slot] = parent[slot] = 0;
314 // we become the child of a former leaf
315 } else if (slot == 0) {
316 int[] left = wentLeft ? BalancedTree.left : BalancedTree.right;
317 int[] right = wentLeft ? BalancedTree.right : BalancedTree.left;
318 // FEATURE: Might be doing too much work here
325 // we take the place of a preexisting node
327 left[arg] = left[slot]; // steal slot's left subtree
329 right[arg] = slot; // make slot our right subtree
330 parent[arg] = parent[slot];
332 if(left[arg] != 0) parent[left[arg]] = arg;
338 if (left[p] == slot) left[p] = arg;
339 else if (right[p] == slot) right[p] = arg;
340 else throw new Error("should never happen");
348 // Retrieval //////////////////////////////////////////////////////////////////////
350 private int get(int index, int slot) {
351 int diff = index - sizeof(left[slot]);
352 if (diff > 0) return get(diff - 1, right[slot]);
353 else if (diff < 0) return get(index, left[slot]);
358 // Deletion //////////////////////////////////////////////////////////////////////
360 private int delete(int index, int slot, int p) {
361 int diff = index - sizeof(left[slot]);
363 int ret = delete(index, left[slot], slot);
367 } else if (diff > 0) {
368 int ret = delete(diff - 1, right[slot], slot);
372 // we found the node to delete
375 // fast path: it has no children
376 if (left[slot] == 0 && right[slot] == 0) {
377 if (p == 0) root = 0;
379 int[] side = left[p] == slot ? left : right;
380 side[p] = side[slot]; // fix parent's pointer
383 // fast path: it has no left child, so we replace it with its right child
384 } else if (left[slot] == 0) {
385 if (p == 0) root = right[slot];
386 else (left[p] == slot ? left : right)[p] = right[slot]; // fix parent's pointer
387 parent[right[slot]] = p;
388 left[leftmost(right[slot])] = left[slot]; // fix our successor-leaf's fake right ptr
389 balance(right[slot], p);
391 // fast path; it has no right child, so we replace it with its left child
392 } else if (right[slot] == 0) {
393 if (p == 0) root = left[slot];
394 else (left[p] == slot ? left : right)[p] = left[slot]; // fix parent's pointer
395 parent[left[slot]] = p;
396 right[rightmost(left[slot])] = right[slot]; // fix our successor-leaf's fake right ptr
397 balance(left[slot], p);
399 // node to be deleted has two children, so we replace it with its left child's rightmost descendant
401 int left_childs_rightmost = delete(sizeof(left[slot]) - 1, left[slot], slot);
402 left[left_childs_rightmost] = left[slot];
403 right[left_childs_rightmost] = right[slot];
404 if(left[slot] != 0) parent[left[slot]] = left_childs_rightmost;
405 if(right[slot] != 0) parent[right[slot]] = left_childs_rightmost;
406 parent[left_childs_rightmost] = parent[slot];
407 if (p == 0) root = left_childs_rightmost;
408 else (left[p] == slot ? left : right)[p] = left_childs_rightmost; // fix parent's pointer
409 balance(left_childs_rightmost, p);
416 protected void finalize() { clear(); }
418 public void printTree() {
419 if(root == 0) System.err.println("Tree is empty");
420 else printTree(root,0,false);
423 private void printTree(int node,int indent,boolean l) {
424 for(int i=0;i<indent;i++) System.err.print(" ");
425 if(node == 0) System.err.println("None");
427 System.err.print("" + node + ": " + objects[node]);
428 System.err.println(" Parent: " + parent[node] + " Size: " + size[node]);
429 printTree(left[node],indent+1,true);
430 printTree(right[node],indent+1,false);