2003/11/28 03:06:56
[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 = 0;
19     private int cached_slot = 0;
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 = 0;
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 = 0;
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 (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         else 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         int distance = Math.abs(index - cached_index);
68
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 (cached_index != 0 && (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         return objects[get(index, root)];
79     }
80
81     /** deletes the object at index, returning the deleted object */
82     public final Object deleteNode(int index) {
83         // FIXME handle root deletion here
84         cached_slot = cached_index = 0;
85         int del = delete(index, root, 0);
86         left[del] = right[del] = size[del] = 0;
87         Object ret = objects[del];
88         objects[del] = null;
89         return ret;
90     }
91
92
93     // Node Data /////////////////////////////////////////////////////////////////////////
94
95     private final static int NUM_SLOTS = 64 * 1024;
96
97     /**
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.
104      */
105     private static Object[] objects = new Object[NUM_SLOTS];
106     private static int[] left = new int[NUM_SLOTS];      ///< if positive: left child's slot; if negative: predecessor's slot
107     private static int[] right = new int[NUM_SLOTS];     ///< if positive: right child's slot; if negative: successor's slot
108     private static int[] size = new int[NUM_SLOTS];      ///< the number of descendants of this node *including the node itself*
109
110
111     // Slot Management //////////////////////////////////////////////////////////////////////
112
113     /** returns the slot holding object o; use null to allocate a new slot */
114     private int getSlot(Object o, int hash) {
115         // FIXME: check for full table
116         int dest = Math.abs(hash) % objects.length;
117         int odest = dest;
118         boolean plus = true;
119         int tries = 1;
120         while (objects[dest] != o) {
121             if (dest == 0) dest++;
122             dest = Math.abs((odest + (plus ? 1 : -1) * tries * tries) % objects.length);
123             if (plus) tries++;
124             plus = !plus;
125         }
126         return dest;
127     }
128
129     /** allocates a new slot */
130     private int allocateSlot(Object o) {
131         // we XOR with our own hashcode so that we don't get tons of
132         // collisions when a single Object is inserted into multiple
133         // trees
134         int slot = getSlot(null, o.hashCode() ^ this.hashCode());
135         objects[slot] = o;
136         return slot;
137     }
138
139
140
141     // Helpers /////////////////////////////////////////////////////////////////////////
142
143     private final int leftmost(int slot) { return left[slot] <= 0 ? slot : leftmost(left[slot]); }
144     private final int rightmost(int slot) { return right[slot] <= 0 ? slot : rightmost(right[slot]); }
145     private final int next(int slot) { return right[slot] <= 0 ? -1 * right[slot] : leftmost(right[slot]); }
146     private final int prev(int slot) { return left[slot] <= 0 ? -1 * left[slot] : rightmost(left[slot]); }
147     private final int size(int slot) { return slot <= 0 ? 0 : size[slot]; }
148
149
150     // Rotation and Balancing /////////////////////////////////////////////////////////////
151
152     //    parent             parent
153     //      |                  |
154     //      b                  d 
155     //     / \                / \
156     //    a   d    < == >    b   e
157     //       / \            / \
158     //      c   e          a   c
159     // FIXME might be doing too much work here
160     private void rotate(boolean toTheLeft, int b, int parent) {
161         int[] left = toTheLeft ? BalancedTree.left : BalancedTree.right;
162         int[] right = toTheLeft ? BalancedTree.right : BalancedTree.left;
163         int d = right[b];
164         int c = left[d];
165         left[d] = b;
166         right[b] = c;
167         if (parent == 0)              root = d;
168         else if (left[parent] == b)   left[parent] = d;
169         else if (right[parent] == b)  right[parent] = d;
170         else throw new Error("rotate called with invalid parent");
171         size[b] = 1 + size(left[b]) + size(right[b]);
172         balance(b, d);
173         size[d] = 1 + size(left[d]) + size(right[d]);
174         balance(d, parent);
175     }
176
177     private void balance(int slot, int parent) {
178         if (size(left[slot]) - 1 > 2 * size(right[slot])) rotate(false, slot, parent);
179         else if (size(left[slot]) * 2 < size(right[slot]) - 1) rotate(true, slot, parent);
180         size[slot] = 1 + size(left[slot]) + size(right[slot]);
181     }
182
183
184
185     // Insert /////////////////////////////////////////////////////////////////////////
186
187     private void insert(int index, int arg, int slot, int parent, boolean replace, boolean wentLeft) {
188         int diff = slot <= 0 ? 0 : index - size(left[slot]);
189         if (slot > 0 && diff != 0) {
190             if (diff < 0) insert(index, arg, left[slot], slot, replace, true);
191             else insert(index - size(left[slot]) - 1, arg, right[slot], slot, replace, false);
192             balance(slot, parent);
193             return;
194         }
195
196         if (size[arg] != 0) throw new Error("double insertion");
197
198         // we become the child of a former leaf
199         if (slot <= 0) {
200             int[] left = wentLeft ? BalancedTree.left : BalancedTree.right;
201             int[] right = wentLeft ? BalancedTree.right : BalancedTree.left;
202             left[arg] = slot;
203             left[parent] = arg;
204             right[arg] = -1 * parent;
205             balance(arg, parent);
206
207         // we take the place of a preexisting node
208         } else {
209             left[arg] = left[slot];   // steal slot's left subtree
210             left[slot] = -1 * arg;
211             right[arg] = slot;        // make slot our right subtree
212             if (slot == root) {
213                 root = arg;
214                 balance(slot, arg);
215             } else {
216                 (left[parent] == slot ? left : right)[parent] = arg;
217                 balance(slot, arg);
218                 balance(arg, parent);
219             }
220         }
221     }
222
223
224     // Retrieval //////////////////////////////////////////////////////////////////////
225
226     private int get(int index, int slot) {
227         int diff = index - size(left[slot]);
228         if (diff > 0) return get(diff - 1, right[slot]);
229         else if (diff < 0) return get(index, left[slot]);
230         else return slot;
231     }
232
233
234     // Deletion //////////////////////////////////////////////////////////////////////
235
236     private int delete(int index, int slot, int parent) {
237         int diff = index - size(left[slot]);
238         if (diff < 0) {
239             int ret = delete(index, left[slot], slot);
240             balance(slot, parent);
241             return ret;
242
243         } else if (diff > 0) {
244             int ret = delete(diff - 1, right[slot], slot);
245             balance(slot, parent);
246             return ret;
247
248         // we found the node to delete
249         } else {
250
251             // fast path: it has no left child, so we replace it with its right child
252             if (left[slot] < 0) {
253                 (left[parent] == slot ? left : right)[parent] = right[slot];          // fix parent's pointer
254                 if (right[slot] > 0) left[leftmost(right[slot])] = left[slot];        // fix our successor-leaf's fake left ptr
255                 balance(right[slot], parent);
256
257             // fast path; it has no right child, so we replace it with its left child
258             } else if (right[slot] < 0) {
259                 (left[parent] == slot ? left : right)[parent] = left[slot];           // fix parent's pointer
260                 if (left[slot] > 0) right[rightmost(left[slot])] = right[slot];       // fix our successor-leaf's fake right ptr
261                 balance(left[slot], parent);
262
263             // node to be deleted has two children, so we replace it with its left child's rightmost descendant
264             } else {
265                 int left_childs_rightmost = delete(size(left[slot]) - 1, left[slot], slot);
266                 left[left_childs_rightmost] = left[slot];
267                 left[left_childs_rightmost] = right[slot];
268                 (left[parent] == slot ? left : right)[parent] = left_childs_rightmost;     // fix parent's pointer
269                 balance(left_childs_rightmost, parent);
270             }
271
272             return slot;
273         }
274     }
275
276 }