1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
4 // FEATURE: private void intersection() { }
5 // FEATURE: private void union() { }
6 // FEATURE: private void subset() { }
7 // FEATURE: grow if we run out of slots
10 /** a weight-balanced tree with fake leaves */
11 public class BalancedTree {
14 // Instance Variables ///////////////////////////////////////////////////////////////////
16 private int root = 0; ///< the slot of the root element
18 private int cached_index = -1;
19 private int cached_slot = -1;
21 // Public API //////////////////////////////////////////////////////////////////////////
23 /** the number of elements in the tree */
24 public final int treeSize() { return root == 0 ? 0 : size[root]; }
26 /** clamps index to [0..treeSize()] and inserts object o *before* the specified index */
27 public final void insertNode(int index, Object o) {
28 cached_slot = cached_index = -1;
29 if (index < 0) index = 0;
30 if (index > treeSize()) index = treeSize();
31 int arg = allocateSlot(o);
32 if (root != 0) { insert(index, arg, root, 0, false, false); return; }
39 /** clamps index to [0..treeSize()-1] and replaces the object at that index with object o */
40 public final void replaceNode(int index, Object o) {
41 cached_slot = cached_index = -1;
42 if (index < 0) index = 0;
43 if (index > treeSize()) index = treeSize() - 1;
44 int arg = allocateSlot(o);
45 if (root != 0) { insert(index, arg, root, 0, true, false); return; }
51 /** returns the index of o; runs in O((log n)^2) time unless cache hit */
52 public final int indexNode(Object o) {
53 if (cached_slot != -1 && objects[cached_slot] == o) return cached_index;
55 int slot = getSlot(o, o.hashCode() ^ this.hashCode());
56 int parent = -1 * left[leftmost(slot)];
57 if (parent == 0) return size(left[slot]); // we are on the far left edge
59 // all nodes after parent and before us are in our left subtree
60 return size(left[slot]) + indexNode(objects[parent]) + 1;
63 /** returns the object at index; runs in O(log n) time unless cache hit */
64 public final Object getNode(int index) {
65 if (index == cached_index) return objects[cached_slot];
67 if (cached_index != -1) {
68 int distance = Math.abs(index - cached_index);
69 // if the in-order distance between the cached node and the
70 // target node is less than log(n), it's probably faster to
72 if ((distance < 16) && ((2 << distance) < treeSize())) {
73 while(cached_index > index) { cached_slot = prev(cached_slot); cached_index--; }
74 while(cached_index < index) { cached_slot = next(cached_slot); cached_index++; }
75 return objects[cached_slot];
79 return objects[get(index, root)];
82 /** deletes the object at index, returning the deleted object */
83 public final Object deleteNode(int index) {
84 cached_slot = cached_index = -1;
85 int del = delete(index, root, 0);
86 left[del] = right[del] = size[del] = 0;
87 Object ret = objects[del];
93 // Node Data /////////////////////////////////////////////////////////////////////////
95 private final static int NUM_SLOTS = 64 * 1024;
98 * Every object inserted into *any* tree gets a "slot" in this
99 * array. The slot is determined by hashcode modulo the length of
100 * the array, with quadradic probing to resolve collisions. NOTE
101 * that the "slot" of a node is NOT the same as its index.
102 * Furthermore, if an object is inserted into multiple trees, that
103 * object will have multiple slots.
105 private static Object[] objects = new Object[NUM_SLOTS];
107 /// These two arrays hold the left and right children of each
108 /// slot; in other words, left[x] is the *slot* of the left child
109 /// of the node in slot x.
111 /// If x has no left child, then left[x] is -1 multiplied by the
112 /// slot of the node that precedes x; if x is the first node, then
113 /// left[x] is 0. The right[] array works the same way.
115 private static int[] left = new int[NUM_SLOTS];
116 private static int[] right = new int[NUM_SLOTS];
118 ///< the number of descendants of this node *including the node itself*
119 private static int[] size = new int[NUM_SLOTS];
122 // Slot Management //////////////////////////////////////////////////////////////////////
124 /** returns the slot holding object o; use null to allocate a new slot */
125 private int getSlot(Object o, int hash) {
126 // FIXME: check for full table
127 int dest = Math.abs(hash) % objects.length;
131 while (objects[dest] != o) {
132 if (dest == 0) dest++;
133 dest = Math.abs((odest + (plus ? 1 : -1) * tries * tries) % objects.length);
140 /** allocates a new slot */
141 private int allocateSlot(Object o) {
142 // we XOR with our own hashcode so that we don't get tons of
143 // collisions when a single Object is inserted into multiple
145 int slot = getSlot(null, o.hashCode() ^ this.hashCode());
152 // Helpers /////////////////////////////////////////////////////////////////////////
154 private final int leftmost(int slot) { return left[slot] <= 0 ? slot : leftmost(left[slot]); }
155 private final int rightmost(int slot) { return right[slot] <= 0 ? slot : rightmost(right[slot]); }
156 private final int next(int slot) { return right[slot] <= 0 ? -1 * right[slot] : leftmost(right[slot]); }
157 private final int prev(int slot) { return left[slot] <= 0 ? -1 * left[slot] : rightmost(left[slot]); }
158 private final int size(int slot) { return slot <= 0 ? 0 : size[slot]; }
161 // Rotation and Balancing /////////////////////////////////////////////////////////////
170 // FIXME might be doing too much work here
171 private void rotate(boolean toTheLeft, int b, int parent) {
172 int[] left = toTheLeft ? BalancedTree.left : BalancedTree.right;
173 int[] right = toTheLeft ? BalancedTree.right : BalancedTree.left;
176 if (d <= 0) throw new Error("rotation error");
179 if (parent == 0) root = d;
180 else if (left[parent] == b) left[parent] = d;
181 else if (right[parent] == b) right[parent] = d;
182 else throw new Error("rotate called with invalid parent");
187 private void balance(int slot, int parent) {
188 if (slot <= 0) return;
189 size[slot] = 1 + size(left[slot]) + size(right[slot]);
190 if (size(left[slot]) - 1 > 2 * size(right[slot])) rotate(false, slot, parent);
191 else if (size(left[slot]) * 2 < size(right[slot]) - 1) rotate(true, slot, parent);
196 // Insert /////////////////////////////////////////////////////////////////////////
198 private void insert(int index, int arg, int slot, int parent, boolean replace, boolean wentLeft) {
199 int diff = slot <= 0 ? 0 : index - size(left[slot]);
200 if (slot > 0 && diff != 0) {
201 if (diff < 0) insert(index, arg, left[slot], slot, replace, true);
202 else insert(index - size(left[slot]) - 1, arg, right[slot], slot, replace, false);
203 balance(slot, parent);
207 if (size[arg] != 0) throw new Error("double insertion");
209 // we become the child of a former leaf
211 int[] left = wentLeft ? BalancedTree.left : BalancedTree.right;
212 int[] right = wentLeft ? BalancedTree.right : BalancedTree.left;
215 right[arg] = -1 * parent;
216 balance(arg, parent);
218 // we take the place of a preexisting node
220 left[arg] = left[slot]; // steal slot's left subtree
221 left[slot] = -1 * arg;
222 right[arg] = slot; // make slot our right subtree
227 (left[parent] == slot ? left : right)[parent] = arg;
229 balance(arg, parent);
235 // Retrieval //////////////////////////////////////////////////////////////////////
237 private int get(int index, int slot) {
238 int diff = index - size(left[slot]);
239 if (diff > 0) return get(diff - 1, right[slot]);
240 else if (diff < 0) return get(index, left[slot]);
245 // Deletion //////////////////////////////////////////////////////////////////////
247 private int delete(int index, int slot, int parent) {
248 int diff = index - size(left[slot]);
250 int ret = delete(index, left[slot], slot);
251 balance(slot, parent);
254 } else if (diff > 0) {
255 int ret = delete(diff - 1, right[slot], slot);
256 balance(slot, parent);
259 // we found the node to delete
262 // fast path: it has no children
263 if (left[slot] <= 0 && right[slot] <= 0) {
264 if (parent == 0) root = 0;
266 int[] side = left[parent] == slot ? left : right;
267 side[parent] = side[slot]; // fix parent's pointer
270 // fast path: it has no left child, so we replace it with its right child
271 } else if (left[slot] <= 0) {
272 if (parent == 0) root = right[slot];
273 else (left[parent] == slot ? left : right)[parent] = right[slot]; // fix parent's pointer
274 if (right[slot] > 0) left[leftmost(right[slot])] = left[slot]; // fix our successor-leaf's fake right ptr
275 balance(right[slot], parent);
277 // fast path; it has no right child, so we replace it with its left child
278 } else if (right[slot] <= 0) {
279 if (parent == 0) root = left[slot];
280 else (left[parent] == slot ? left : right)[parent] = left[slot]; // fix parent's pointer
281 if (left[slot] > 0) right[rightmost(left[slot])] = right[slot]; // fix our successor-leaf's fake right ptr
282 balance(left[slot], parent);
284 // node to be deleted has two children, so we replace it with its left child's rightmost descendant
286 int left_childs_rightmost = delete(size(left[slot]) - 1, left[slot], slot);
287 left[left_childs_rightmost] = left[slot];
288 left[left_childs_rightmost] = right[slot];
289 if (parent == 0) root = left_childs_rightmost;
290 else (left[parent] == slot ? left : right)[parent] = left_childs_rightmost; // fix parent's pointer
291 balance(left_childs_rightmost, parent);