Rope (data structure)![]() In computer programming, a rope, or cord, is a data structure composed of smaller strings that is used to efficiently store and manipulate longer strings or entire texts. For example, a text editing program may use a rope to represent the text being edited, so that operations such as insertion, deletion, and random access can be done efficiently.[1] DescriptionA rope is a type of binary tree where each leaf (end node) holds a string of manageable size and length (also known as a weight), and each node further up the tree holds the sum of the lengths of all the leaves in its left subtree. A node with two children thus divides the whole string into two parts: the left subtree stores the first part of the string, the right subtree stores the second part of the string, and a node's weight is the length of the first part. For rope operations, the strings stored in nodes are assumed to be constant immutable objects in the typical nondestructive case, allowing for some copy-on-write behavior. Leaf nodes are usually implemented as basic fixed-length strings with a reference count attached for deallocation when no longer needed, although other garbage collection methods can be used as well. OperationsIn the following definitions, N is the length of the rope, that is, the weight of the root node. Collect leaves
final class InOrderRopeIterator implements Iterator<RopeLike> {
private final Deque<RopeLike> stack;
InOrderRopeIterator(@NonNull RopeLike root) {
stack = new ArrayDeque<>();
var c = root;
while (c != null) {
stack.push(c);
c = c.getLeft();
}
}
@Override
public boolean hasNext() {
return stack.size() > 0;
}
@Override
public RopeLike next() {
val result = stack.pop();
if (!stack.isEmpty()) {
var parent = stack.pop();
var right = parent.getRight();
if (right != null) {
stack.push(right);
var cleft = right.getLeft();
while (cleft != null) {
stack.push(cleft);
cleft = cleft.getLeft();
}
}
}
return result;
}
}
Rebalance
static boolean isBalanced(RopeLike r) {
val depth = r.depth();
if (depth >= FIBONACCI_SEQUENCE.length - 2) {
return false;
}
return FIBONACCI_SEQUENCE[depth + 2] <= r.weight();
}
static RopeLike rebalance(RopeLike r) {
if (!isBalanced(r)) {
val leaves = Ropes.collectLeaves(r);
return merge(leaves, 0, leaves.size());
}
return r;
}
static RopeLike merge(List<RopeLike> leaves) {
return merge(leaves, 0, leaves.size());
}
static RopeLike merge(List<RopeLike> leaves, int start, int end) {
int range = end - start;
if (range == 1) {
return leaves.get(start);
}
if (range == 2) {
return new RopeLikeTree(leaves.get(start), leaves.get(start + 1));
}
int mid = start + (range / 2);
return new RopeLikeTree(merge(leaves, start, mid), merge(leaves, mid, end));
}
Insert
This operation can be done by a public Rope insert(int idx, CharSequence sequence) {
if (idx == 0) {
return prepend(sequence);
}
if (idx == length()) {
return append(sequence);
}
val lhs = base.split(idx);
return new Rope(Ropes.concat(lhs.fst.append(sequence), lhs.snd));
}
Index![]()
To retrieve the i-th character, we begin a recursive search from the root node: @Override
public int indexOf(char ch, int startIndex) {
if (startIndex > weight) {
return right.indexOf(ch, startIndex - weight);
}
return left.indexOf(ch, startIndex);
}
For example, to find the character at Concat![]()
A concatenation can be performed simply by creating a new root node with left = S1 and right = S2, which is constant time. The weight of the parent node is set to the length of the left child S1, which would take time, if the tree is balanced. As most rope operations require balanced trees, the tree may need to be re-balanced after concatenation. Split![]()
There are two cases that must be dealt with:
The second case reduces to the first by splitting the string at the split point to create two new leaf nodes, then creating a new node that is the parent of the two component strings. For example, to split the 22-character rope pictured in Figure 2.3 into two equal component ropes of length 11, query the 12th character to locate the node K at the bottom level. Remove the link between K and G. Go to the parent of G and subtract the weight of K from the weight of D. Travel up the tree and remove any right links to subtrees covering characters past position 11, subtracting the weight of K from their parent nodes (only node D and A, in this case). Finally, build up the newly orphaned nodes K and H by concatenating them together and creating a new parent P with weight equal to the length of the left node K. As most rope operations require balanced trees, the tree may need to be re-balanced after splitting. public Pair<RopeLike, RopeLike> split(int index) {
if (index < weight) {
val split = left.split(index);
return Pair.of(rebalance(split.fst), rebalance(new RopeLikeTree(split.snd, right)));
} else if (index > weight) {
val split = right.split(index - weight);
return Pair.of(rebalance(new RopeLikeTree(left, split.fst)), rebalance(split.snd));
} else {
return Pair.of(left, right);
}
}
Delete
This operation can be done by two @Override
public RopeLike delete(int start, int length) {
val lhs = split(start);
val rhs = split(start + length);
return rebalance(new RopeLikeTree(lhs.fst, rhs.snd));
}
Report
To report the string Ci, …, Ci + j − 1, find the node u that contains Ci and Comparison with monolithic arrays
Advantages:
Disadvantages:
This table compares the algorithmic traits of string and rope implementations, not their raw speed. Array-based strings have smaller overhead, so (for example) concatenation and split operations are faster on small datasets. However, when array-based strings are used for longer strings, time complexity and memory use for inserting and deleting characters becomes unacceptably large. In contrast, a rope data structure has stable performance regardless of data size. Further, the space complexity for ropes and arrays are both O(n). In summary, ropes are preferable when the data is large and modified often. See also
References
External linksWikimedia Commons has media related to Rope (data structure).
|
Portal di Ensiklopedia Dunia