2003/11/27 05:05:10
[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
9 /** a weight-balanced tree with fake leaves */
10 public class BalancedTree {
11
12
13     // Instance Variables ///////////////////////////////////////////////////////////////////
14
15     private int root = 0;                         ///< the slot of the root element
16
17
18     // Public API //////////////////////////////////////////////////////////////////////////
19
20     /** the number of elements in the tree */
21     public final int treeSize() { return root == 0 ? 0 : size[root]; }
22
23     /** clamps index to [0..treeSize()] and inserts object o *before* the specified index */
24     public final void insertNode(int index, Object o) {
25         if (index < 0) index = 0;
26         if (index > treeSize()) index = treeSize();
27         int arg = allocateSlot(o);
28         if (root != 0) { insert(index, arg, root, 0, false, false); return; }
29         root = arg;
30         left[arg] = 0;
31         right[arg] = 0;
32         size[root] = 1;
33     }
34
35     /** clamps index to [0..treeSize()-1] and replaces the object at that index with object o */
36     public final void replaceNode(int index, Object o) {
37         if (index < 0) index = 0;
38         if (index > treeSize()) index = treeSize() - 1;
39         int arg = allocateSlot(o);
40         if (root != 0) { insert(index, arg, root, 0, true, false); return; }
41         root = arg;
42         left[arg] = 0;
43         right[arg] = 0;
44     }
45
46     /** returns the index of o; runs in O((log n)^2) time */
47     public final int indexNode(Object o) { 
48         int slot = getSlot(o, o.hashCode() ^ this.hashCode());
49         int parent = -1 * left[leftmost(slot)];
50         if (parent == 0) return size(left[slot]);             // we are on the far left edge
51
52         // all nodes after parent and before us are in our left subtree
53         else return size(left[slot]) + indexNode(objects[parent]) + 1;
54     }
55
56     /** returns the object at index; runs in O(log n) time */
57     public final Object getNode(int index) {
58         return objects[get(index, root)];
59     }
60
61     /** deletes the object at index, returning the deleted object */
62     public final Object deleteNode(int index) {
63         return delete(index, root, 0);
64     }
65
66
67     // Node Data /////////////////////////////////////////////////////////////////////////
68
69     private final static int NUM_SLOTS = 265 * 1024;
70
71     /**
72      * Every object inserted into *any* tree gets a "slot" in this
73      * array.  The slot is determined by hashcode modulo the length of
74      * the array, with quadradic probing to resolve collisions.  NOTE
75      * that the "slot" of a node is NOT the same as its index.
76      * Furthermore, if an object is inserted into multiple trees, that
77      * object will have multiple slots.
78      */
79     private static Object[] objects = new Object[NUM_SLOTS];
80     private static int[] left = new int[NUM_SLOTS];      ///< if positive: left child's slot; if negative: predecessor's slot
81     private static int[] right = new int[NUM_SLOTS];     ///< if positive: right child's slot; if negative: successor's slot
82     private static int[] size = new int[NUM_SLOTS];      ///< the number of descendants of this node *including the node itself*
83
84
85     // Slot Management //////////////////////////////////////////////////////////////////////
86
87     /** returns the slot holding object o; use null to allocate a new slot */
88     private int getSlot(Object o, int hash) {
89         // FIXME: check for full table
90         int dest = Math.abs(hash) % objects.length;
91         int odest = dest;
92         boolean plus = true;
93         int tries = 1;
94         while (objects[dest] != o) {
95             if (dest == 0) dest++;
96             dest = Math.abs((odest + (plus ? 1 : -1) * tries * tries) % objects.length);
97             if (plus) tries++;
98             plus = !plus;
99         }
100         return dest;
101     }
102
103     /** allocates a new slot */
104     private int allocateSlot(Object o) {
105         // we XOR with our own hashcode so that we don't get tons of
106         // collisions when a single Object is inserted into multiple
107         // trees
108         int slot = getSlot(null, o.hashCode() ^ this.hashCode());
109         objects[slot] = o;
110         return slot;
111     }
112
113
114
115     // Helpers /////////////////////////////////////////////////////////////////////////
116
117     private final int leftmost(int slot) { return left[slot] <= 0 ? slot : leftmost(left[slot]); }
118     private final int rightmost(int slot) { return right[slot] <= 0 ? slot : rightmost(right[slot]); }
119     private final int next(int slot) { return right[slot] <= 0 ? -1 * right[slot] : leftmost(right[slot]); }
120     private final int prev(int slot) { return left[slot] <= 0 ? -1 * left[slot] : rightmost(left[slot]); }
121     private final int size(int slot) { return slot <= 0 ? 0 : size[slot]; }
122
123
124     // Rotation and Balancing /////////////////////////////////////////////////////////////
125
126     //    parent             parent
127     //      |                  |
128     //      b                  d 
129     //     / \                / \
130     //    a   d    < == >    b   e
131     //       / \            / \
132     //      c   e          a   c
133     private void rotate(boolean toTheLeft, int b, int parent) {
134         int[] left = toTheLeft ? BalancedTree.left : BalancedTree.right;
135         int[] right = toTheLeft ? BalancedTree.right : BalancedTree.left;
136         int d = right[b];
137         int c = left[d];
138         left[d] = b;
139         right[b] = c;
140         size[b] = size(left[b]) + size(c);
141         size[d] = size[b] + size(right[d]);
142         if (parent == 0)              root = d;
143         else if (left[parent] == b)   left[parent] = d;
144         else if (right[parent] == b)  right[parent] = d;
145         else throw new Error("rotate called with invalid parent");
146     }
147
148     private void balance(int slot, int parent) {
149         /*
150         if (size(left[slot]) - 1 > 2 * size(right[slot])) rotate(false, slot, parent);
151         else if (size(left[slot]) * 2 < size(right[slot]) - 1) rotate(true, slot, parent);
152         */
153         size[slot] = 1 + size(left[slot]) + size(right[slot]);
154     }
155
156
157
158     // Insert /////////////////////////////////////////////////////////////////////////
159
160     private void insert(int index, int arg, int slot, int parent, boolean replace, boolean wentLeft) {
161         int diff = slot <= 0 ? 0 : index - size(left[slot]);
162         if (slot > 0 && diff != 0) {
163             if (diff < 0) insert(index, arg, left[slot], slot, replace, true);
164             else insert(index - size(left[slot]) - 1, arg, right[slot], slot, replace, false);
165             balance(slot, parent);
166             return;
167         }
168
169         if (size[arg] != 0) throw new Error("double insertion");
170
171         // we become the child of a former leaf
172         if (slot <= 0) {
173             int[] left = wentLeft ? BalancedTree.left : BalancedTree.right;
174             int[] right = wentLeft ? BalancedTree.right : BalancedTree.left;
175             left[arg] = slot;
176             left[parent] = arg;
177             right[arg] = -1 * parent;
178             balance(arg, parent);
179
180         // we take the place of a preexisting node
181         } else {
182             left[arg] = left[slot];   // steal slot's left subtree
183             left[slot] = -1 * arg;
184             right[arg] = slot;        // make slot our right subtree
185             if (slot == root) root = arg;
186             (left[parent] == slot ? left : right)[parent] = arg;
187             balance(slot, arg);
188             balance(arg, parent);
189         }
190     }
191
192
193     // Retrieval //////////////////////////////////////////////////////////////////////
194
195     private int get(int index, int slot) {
196         int diff = index - size(left[slot]);
197         if (diff > 0) return get(diff - 1, right[slot]);
198         else if (diff < 0) return get(index, left[slot]);
199         else return slot;
200     }
201
202
203     // Deletion //////////////////////////////////////////////////////////////////////
204
205     private Object delete(int index, int slot, int parent) {
206         int diff = index - size(left[slot]);
207         if (diff < 0) {
208             Object ret = delete(index, left[slot], slot);
209             balance(slot, parent);
210             return ret;
211
212         } else if (diff > 0) {
213             Object ret = delete(diff - 1, right[slot], slot);
214             balance(slot, parent);
215             return ret;
216
217         } else {
218             if (left[slot] == 0) {
219                 if (parent == 0) root = right[slot];
220                 else (left[parent] == slot ? left : right)[parent] = right[slot];
221                 right[slot] = 0;
222                 balance(slot, parent);
223             } else if (right[slot] == 0) {
224                 if (parent == 0) root = left[slot];
225                 else (left[parent] == slot ? left : right)[parent] = left[slot];
226                 left[slot] = 0;
227                 balance(slot, parent);
228             } else {
229                 Object replacement_object = delete(index - 1, slot, parent);
230                 int replacement = allocateSlot(replacement_object);
231                 if (replacement != 0) {
232                     left[replacement] = left[slot];
233                     right[replacement] = right[slot];
234                 }
235                 if (parent == 0) root = replacement;
236                 else (left[parent] == slot ? left : right)[parent] = replacement;
237                 left[slot] = 0;
238                 right[slot] = 0;
239                 balance(replacement, parent);
240             }
241             Object ret = objects[slot];
242             size[slot] = 0;
243             objects[slot] = null;
244             return ret;
245         }
246     }
247
248 }