2003/11/30 02:06:32
[org.ibex.core.git] / src / org / xwt / util / BalancedTree.java
1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt.util;
3
4 // FEATURE: private void intersection() { }
5 // FEATURE: private void union() { }
6 // FEATURE: private void subset() { }
7 // FEATURE: grow if we run out of slots
8 // FEATURE: finalizer
9
10 /** a weight-balanced tree with fake leaves */
11 public class BalancedTree {
12
13
14     // Instance Variables ///////////////////////////////////////////////////////////////////
15
16     private int root = 0;                         ///< the slot of the root element
17
18     private int cached_index = -1;
19     private int cached_slot = -1;
20
21     // Public API //////////////////////////////////////////////////////////////////////////
22
23     /** the number of elements in the tree */
24     public final int treeSize() { return root == 0 ? 0 : size[root]; }
25
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; }
33         root = arg;
34         left[arg] = 0;
35         right[arg] = 0;
36         size[root] = 1;
37     }
38
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; }
46         root = arg;
47         left[arg] = 0;
48         right[arg] = 0;
49     }
50
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;
54
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
58
59         // all nodes after parent and before us are in our left subtree
60         return size(left[slot]) + indexNode(objects[parent]) + 1;
61     }
62
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];
66
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
71             // search directly.
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];
76             }
77         }
78         /*
79         cached_index = index;
80         cached_slot = get(index, root);
81         return objects[cached_slot];
82         */
83         return objects[get(index, root)];
84     }
85
86     /** deletes the object at index, returning the deleted object */
87     public final Object deleteNode(int index) {
88         cached_slot = cached_index = -1;
89         int del = delete(index, root, 0);
90         left[del] = right[del] = size[del] = 0;
91         Object ret = objects[del];
92         objects[del] = null;
93         return ret;
94     }
95
96
97     // Node Data /////////////////////////////////////////////////////////////////////////
98
99     private final static int NUM_SLOTS = 64 * 1024;
100
101     /**
102      * Every object inserted into *any* tree gets a "slot" in this
103      * array.  The slot is determined by hashcode modulo the length of
104      * the array, with quadradic probing to resolve collisions.  NOTE
105      * that the "slot" of a node is NOT the same as its index.
106      * Furthermore, if an object is inserted into multiple trees, that
107      * object will have multiple slots.
108      */
109     private static Object[] objects = new Object[NUM_SLOTS];
110
111     /// These two arrays hold the left and right children of each
112     /// slot; in other words, left[x] is the *slot* of the left child
113     /// of the node in slot x.
114     ///
115     /// If x has no left child, then left[x] is -1 multiplied by the
116     /// slot of the node that precedes x; if x is the first node, then
117     /// left[x] is 0.  The right[] array works the same way.
118     ///
119     private static int[] left = new int[NUM_SLOTS];
120     private static int[] right = new int[NUM_SLOTS];
121
122     ///< the number of descendants of this node *including the node itself*
123     private static int[] size = new int[NUM_SLOTS];
124
125
126     // Slot Management //////////////////////////////////////////////////////////////////////
127
128     /** returns the slot holding object o; use null to allocate a new slot */
129     private int getSlot(Object o, int hash) {
130         // FIXME: check for full table
131         int dest = Math.abs(hash) % objects.length;
132         int odest = dest;
133         boolean plus = true;
134         int tries = 1;
135         while (objects[dest] != o) {
136             if (dest == 0) dest++;
137             dest = Math.abs((odest + (plus ? 1 : -1) * tries * tries) % objects.length);
138             if (plus) tries++;
139             plus = !plus;
140         }
141         return dest;
142     }
143
144     /** allocates a new slot */
145     private int allocateSlot(Object o) {
146         // we XOR with our own hashcode so that we don't get tons of
147         // collisions when a single Object is inserted into multiple
148         // trees
149         int slot = getSlot(null, o.hashCode() ^ this.hashCode());
150         objects[slot] = o;
151         return slot;
152     }
153
154
155
156     // Helpers /////////////////////////////////////////////////////////////////////////
157
158     private final int leftmost(int slot) { return left[slot] <= 0 ? slot : leftmost(left[slot]); }
159     private final int rightmost(int slot) { return right[slot] <= 0 ? slot : rightmost(right[slot]); }
160     private final int next(int slot) { return right[slot] <= 0 ? -1 * right[slot] : leftmost(right[slot]); }
161     private final int prev(int slot) { return left[slot] <= 0 ? -1 * left[slot] : rightmost(left[slot]); }
162     private final int size(int slot) { return slot <= 0 ? 0 : size[slot]; }
163
164
165     // Rotation and Balancing /////////////////////////////////////////////////////////////
166
167     //    parent             parent
168     //      |                  |
169     //      b                  d 
170     //     / \                / \
171     //    a   d    < == >    b   e
172     //       / \            / \
173     //      c   e          a   c
174     // FIXME might be doing too much work here
175     private void rotate(boolean toTheLeft, int b, int parent) {
176         int[] left = toTheLeft ? BalancedTree.left : BalancedTree.right;
177         int[] right = toTheLeft ? BalancedTree.right : BalancedTree.left;
178         int d = right[b];
179         int c = left[d];
180         if (d <= 0) throw new Error("rotation error");
181         left[d] = b;
182         right[b] = c;
183         if (parent == 0)              root = d;
184         else if (left[parent] == b)   left[parent] = d;
185         else if (right[parent] == b)  right[parent] = d;
186         else throw new Error("rotate called with invalid parent");
187         balance(b, d);
188         balance(d, parent);
189     }
190
191     private void balance(int slot, int parent) {
192         if (slot <= 0) return;
193         size[slot] = 1 + size(left[slot]) + size(right[slot]);
194         if (size(left[slot]) - 1 > 2 * size(right[slot])) rotate(false, slot, parent);
195         else if (size(left[slot]) * 2 < size(right[slot]) - 1) rotate(true, slot, parent);
196     }
197
198
199
200     // Insert /////////////////////////////////////////////////////////////////////////
201
202     private void insert(int index, int arg, int slot, int parent, boolean replace, boolean wentLeft) {
203         int diff = slot <= 0 ? 0 : index - size(left[slot]);
204         if (slot > 0 && diff != 0) {
205             if (diff < 0) insert(index, arg, left[slot], slot, replace, true);
206             else insert(index - size(left[slot]) - 1, arg, right[slot], slot, replace, false);
207             balance(slot, parent);
208             return;
209         }
210
211         if (size[arg] != 0) throw new Error("double insertion");
212
213         if (replace) {
214             if (diff == 0) {
215                 objects[slot] = objects[arg];
216                 objects[arg] = null;
217                 left[arg] = right[arg] = size[arg] = 0;
218             } else {
219                 // since we already clamped the index
220                 throw new Error("this should never happen");
221             }
222         }
223
224         // we become the child of a former leaf
225         if (slot <= 0) {
226             int[] left = wentLeft ? BalancedTree.left : BalancedTree.right;
227             int[] right = wentLeft ? BalancedTree.right : BalancedTree.left;
228             left[arg] = slot;
229             left[parent] = arg;
230             right[arg] = -1 * parent;
231             balance(arg, parent);
232
233         // we take the place of a preexisting node
234         } else {
235             left[arg] = left[slot];   // steal slot's left subtree
236             left[slot] = -1 * arg;
237             right[arg] = slot;        // make slot our right subtree
238             if (slot == root) {
239                 root = arg;
240                 balance(slot, arg);
241             } else {
242                 (left[parent] == slot ? left : right)[parent] = arg;
243                 balance(slot, arg);
244                 balance(arg, parent);
245             }
246         }
247     }
248
249
250     // Retrieval //////////////////////////////////////////////////////////////////////
251
252     private int get(int index, int slot) {
253         int diff = index - size(left[slot]);
254         if (diff > 0) return get(diff - 1, right[slot]);
255         else if (diff < 0) return get(index, left[slot]);
256         else return slot;
257     }
258
259
260     // Deletion //////////////////////////////////////////////////////////////////////
261
262     private int delete(int index, int slot, int parent) {
263         int diff = index - size(left[slot]);
264         if (diff < 0) {
265             int ret = delete(index, left[slot], slot);
266             balance(slot, parent);
267             return ret;
268
269         } else if (diff > 0) {
270             int ret = delete(diff - 1, right[slot], slot);
271             balance(slot, parent);
272             return ret;
273
274         // we found the node to delete
275         } else {
276
277             // fast path: it has no children
278             if (left[slot] <= 0 && right[slot] <= 0) {
279                 if (parent == 0) root = 0;
280                 else {
281                     int[] side = left[parent] == slot ? left : right;
282                     side[parent] = side[slot];      // fix parent's pointer
283                 }
284                 
285             // fast path: it has no left child, so we replace it with its right child
286             } else if (left[slot] <= 0) {
287                 if (parent == 0) root = right[slot];
288                 else (left[parent] == slot ? left : right)[parent] = right[slot];     // fix parent's pointer
289                 if (right[slot] > 0) left[leftmost(right[slot])] = left[slot];        // fix our successor-leaf's fake right ptr
290                 balance(right[slot], parent);
291
292             // fast path; it has no right child, so we replace it with its left child
293             } else if (right[slot] <= 0) {
294                 if (parent == 0) root = left[slot];
295                 else (left[parent] == slot ? left : right)[parent] = left[slot];      // fix parent's pointer
296                 if (left[slot] > 0) right[rightmost(left[slot])] = right[slot];       // fix our successor-leaf's fake right ptr
297                 balance(left[slot], parent);
298
299             // node to be deleted has two children, so we replace it with its left child's rightmost descendant
300             } else {
301                 int left_childs_rightmost = delete(size(left[slot]) - 1, left[slot], slot);
302                 left[left_childs_rightmost] = left[slot];
303                 left[left_childs_rightmost] = right[slot];
304                 if (parent == 0) root = left_childs_rightmost;
305                 else (left[parent] == slot ? left : right)[parent] = left_childs_rightmost;     // fix parent's pointer
306                 balance(left_childs_rightmost, parent);
307             }
308
309             return slot;
310         }
311     }
312
313 }