context_start_lineno
int64 1
913
| line_no
int64 16
984
| repo
stringclasses 5
values | id
int64 0
416
| target_function_prompt
stringlengths 201
13.6k
| function_signature
stringlengths 201
13.6k
| solution_position
listlengths 2
2
| raw_solution
stringlengths 201
13.6k
| focal_code
stringlengths 201
13.6k
| function_name
stringlengths 2
38
| start_line
int64 1
913
| end_line
int64 16
984
| file_path
stringlengths 10
52
| context
stringlengths 4.52k
9.85k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
230
| 241
|
DataStructures.jl
| 0
|
function Base.intersect!(a::Accumulator, b::Accumulator)
for k in union(keys(a), keys(b)) # union not intersection as we want to check both multiplicities
va = a[k]
vb = b[k]
va >= 0 || throw(MultiplicityException(k, va))
vb >= 0 || throw(MultiplicityException(k, vb))
a[k] = min(va, vb)
drop_nonpositive!(a, k) # Drop any that ended up zero
end
return a
end
|
function Base.intersect!(a::Accumulator, b::Accumulator)
for k in union(keys(a), keys(b)) # union not intersection as we want to check both multiplicities
va = a[k]
vb = b[k]
va >= 0 || throw(MultiplicityException(k, va))
vb >= 0 || throw(MultiplicityException(k, vb))
a[k] = min(va, vb)
drop_nonpositive!(a, k) # Drop any that ended up zero
end
return a
end
|
[
230,
241
] |
function Base.intersect!(a::Accumulator, b::Accumulator)
for k in union(keys(a), keys(b)) # union not intersection as we want to check both multiplicities
va = a[k]
vb = b[k]
va >= 0 || throw(MultiplicityException(k, va))
vb >= 0 || throw(MultiplicityException(k, vb))
a[k] = min(va, vb)
drop_nonpositive!(a, k) # Drop any that ended up zero
end
return a
end
|
function Base.intersect!(a::Accumulator, b::Accumulator)
for k in union(keys(a), keys(b)) # union not intersection as we want to check both multiplicities
va = a[k]
vb = b[k]
va >= 0 || throw(MultiplicityException(k, va))
vb >= 0 || throw(MultiplicityException(k, vb))
a[k] = min(va, vb)
drop_nonpositive!(a, k) # Drop any that ended up zero
end
return a
end
|
Base.intersect!
| 230
| 241
|
src/accumulator.jl
|
#FILE: DataStructures.jl/src/sparse_int_set.jl
##CHUNK 1
#Is there a more performant way to do this?
Base.intersect!(s1::SparseIntSet, ns) = copy!(s1, intersect(s1, ns))
Base.setdiff(s::SparseIntSet, ns) = setdiff!(copy(s), ns)
function Base.setdiff!(s::SparseIntSet, ns)
for n in ns
pop!(s, n, nothing)
end
return s
end
function Base.:(==)(s1::SparseIntSet, s2::SparseIntSet)
length(s1) != length(s2) && return false
return all(in(s1), s2)
end
Base.issubset(a::SparseIntSet, b::SparseIntSet) = isequal(a, intersect(a, b))
Base.:(<)(a::SparseIntSet, b::SparseIntSet) = ( a<=b ) && !isequal(a, b)
Base.:(<=)(a::SparseIntSet, b::SparseIntSet) = issubset(a, b)
#FILE: DataStructures.jl/test/test_int_set.jl
##CHUNK 1
p′ = complement(p)
q′ = complement(q)
function collect10(itr)
r = eltype(itr)[]
for i in itr
i > 10 && break
push!(r, i)
end
r
end
a = Set(p)
b = Set(q)
a′ = Set(collect10(p′))
b′ = Set(collect10(q′))
for f in (union, intersect, setdiff, symdiff)
@test collect(f(p, p)) == sort(collect(f(a, a)))
@test collect(f(q, q)) == sort(collect(f(b, b)))
@test collect(f(p, q)) == sort(collect(f(a, b)))
@test collect(f(q, p)) == sort(collect(f(b, a)))
#FILE: DataStructures.jl/test/test_mutable_binheap.jl
##CHUNK 1
update!(h, 2, 20)
@test isequal(heap_values(h), [0.5, 10.1, 3.0, 20.0])
end
@testset "empty!" begin
vs = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7]
vs2 = collect(enumerate(vs))
ordering = Base.Order.By(last)
for h in (MutableBinaryMinHeap(vs), MutableBinaryMaxHeap(vs), MutableBinaryHeap(ordering, vs2))
@test length(h) == length(vs)
@test !isempty(h)
ret = empty!(h)
@test ret === h
@test length(ret) == 0
@test isempty(ret)
@test verify_heap(ret)
end
end
#FILE: DataStructures.jl/src/int_set.jl
##CHUNK 1
(l1 == l2 || all(unsafe_getindex(s1.bits, l2+1:l1)))
end
end
const hashis_seed = UInt === UInt64 ? 0x88989f1fc7dea67d : 0xc7dea67d
function Base.hash(s::IntSet, h::UInt)
# Only hash the bits array up to the last-set bit to prevent extra empty
# bits from changing the hash result
l = findprev(s.bits, length(s.bits))
return hash(unsafe_getindex(s.bits, 1:l), h) ⊻ hash(s.inverse) ⊻ hashis_seed
end
Base.issubset(a::IntSet, b::IntSet) = isequal(a, intersect(a,b))
Base.:(<)(a::IntSet, b::IntSet) = (a<=b) && !isequal(a,b)
Base.:(<=)(a::IntSet, b::IntSet) = issubset(a, b)
#CURRENT FILE: DataStructures.jl/src/accumulator.jl
##CHUNK 1
va >= 0 || throw(MultiplicityException(kb, va))
a[kb] = max(va, vb)
end
return a
end
Base.intersect(a::Accumulator, b::Accumulator, c::Accumulator...) = intersect(intersect(a,b), c...)
Base.intersect(a::Accumulator, b::Accumulator) = intersect!(copy(a), b)
function Base.show(io::IO, acc::Accumulator{T,V}) where {T,V}
l = length(acc)
if l>0
print(io, "Accumulator(")
else
print(io,"Accumulator{$T,$V}(")
end
for (count, (k, v)) in enumerate(acc)
print(io, k, " => ", v)
if count < l
print(io, ", ")
##CHUNK 2
end
Base.issubset(a::Accumulator, b::Accumulator) = all(b[k] >= v for (k, v) in a)
Base.union(a::Accumulator, b::Accumulator, c::Accumulator...) = union(union(a,b), c...)
Base.union(a::Accumulator, b::Accumulator) = union!(copy(a), b)
function Base.union!(a::Accumulator, b::Accumulator)
for (kb, vb) in b
va = a[kb]
vb >= 0 || throw(MultiplicityException(kb, vb))
va >= 0 || throw(MultiplicityException(kb, va))
a[kb] = max(va, vb)
end
return a
end
Base.intersect(a::Accumulator, b::Accumulator, c::Accumulator...) = intersect(intersect(a,b), c...)
Base.intersect(a::Accumulator, b::Accumulator) = intersect!(copy(a), b)
function Base.show(io::IO, acc::Accumulator{T,V}) where {T,V}
##CHUNK 3
function Base.setdiff(a::Accumulator, b::Accumulator)
ret = copy(a)
for (k, v) in b
v > 0 || throw(MultiplicityException(k, v))
dec!(ret, k, v)
drop_nonpositive!(ret, k)
end
return ret
end
Base.issubset(a::Accumulator, b::Accumulator) = all(b[k] >= v for (k, v) in a)
Base.union(a::Accumulator, b::Accumulator, c::Accumulator...) = union(union(a,b), c...)
Base.union(a::Accumulator, b::Accumulator) = union!(copy(a), b)
function Base.union!(a::Accumulator, b::Accumulator)
for (kb, vb) in b
va = a[kb]
vb >= 0 || throw(MultiplicityException(kb, vb))
##CHUNK 4
k::K
v::V
end
function Base.showerror(io::IO, err::MultiplicityException)
print(io, "When using an `Accumulator` as a multiset, all elements must have positive multiplicity")
print(io, " element `$(err.k)` has multiplicity $(err.v)")
end
drop_nonpositive!(a::Accumulator, k) = (a[k] > 0 || delete!(a.map, k))
function Base.setdiff(a::Accumulator, b::Accumulator)
ret = copy(a)
for (k, v) in b
v > 0 || throw(MultiplicityException(k, v))
dec!(ret, k, v)
drop_nonpositive!(ret, k)
end
return ret
##CHUNK 5
(unless those elements are added to he accumulator directly, eg via `acc[foo]=0)
"""
nsmallest(acc::Accumulator) = sort!(collect(acc), by=last, rev=false)
nsmallest(acc::Accumulator, n) = partialsort!(collect(acc), 1:n, by=last, rev=false)
###########################################################
## Multiset operations
struct MultiplicityException{K, V} <: Exception
k::K
v::V
end
function Base.showerror(io::IO, err::MultiplicityException)
print(io, "When using an `Accumulator` as a multiset, all elements must have positive multiplicity")
print(io, " element `$(err.k)` has multiplicity $(err.v)")
end
drop_nonpositive!(a::Accumulator, k) = (a[k] > 0 || delete!(a.map, k))
##CHUNK 6
ct = copy(ct1)
merge!(ct,others...)
end
"""
reset!(ct::Accumulator, x)
Remove a key `x` from an accumulator, and return its current value
"""
reset!(ct::Accumulator{<:Any,V}, x) where V = haskey(ct.map, x) ? pop!(ct.map, x) : zero(V)
"""
nlargest(acc::Accumulator, [n])
Returns a sorted vector of the `n` most common elements, with their counts.
If `n` is omitted, the full sorted collection is returned.
This corresponds to Python's `Counter.most_common` function.
Example
|
83
| 93
|
DataStructures.jl
| 1
|
function left_rotate(z::AVLTreeNode)
y = z.rightChild
α = y.leftChild
y.leftChild = z
z.rightChild = α
z.height = compute_height(z)
y.height = compute_height(y)
z.subsize = compute_subtree_size(z)
y.subsize = compute_subtree_size(y)
return y
end
|
function left_rotate(z::AVLTreeNode)
y = z.rightChild
α = y.leftChild
y.leftChild = z
z.rightChild = α
z.height = compute_height(z)
y.height = compute_height(y)
z.subsize = compute_subtree_size(z)
y.subsize = compute_subtree_size(y)
return y
end
|
[
83,
93
] |
function left_rotate(z::AVLTreeNode)
y = z.rightChild
α = y.leftChild
y.leftChild = z
z.rightChild = α
z.height = compute_height(z)
y.height = compute_height(y)
z.subsize = compute_subtree_size(z)
y.subsize = compute_subtree_size(y)
return y
end
|
function left_rotate(z::AVLTreeNode)
y = z.rightChild
α = y.leftChild
y.leftChild = z
z.rightChild = α
z.height = compute_height(z)
y.height = compute_height(y)
z.subsize = compute_subtree_size(z)
y.subsize = compute_subtree_size(y)
return y
end
|
left_rotate
| 83
| 93
|
src/avl_tree.jl
|
#FILE: DataStructures.jl/src/red_black_tree.jl
##CHUNK 1
node_x.parent.rightChild = node_y
end
node_y.leftChild = node_x
node_x.parent = node_y
end
"""
right_rotate!(tree::RBTree, node_x::RBTreeNode)
Performs a right-rotation on `node_x` and updates `tree.root`, if required.
"""
function right_rotate!(tree::RBTree, node_x::RBTreeNode)
node_y = node_x.leftChild
node_x.leftChild = node_y.rightChild
if node_y.rightChild !== tree.nil
node_y.rightChild.parent = node_x
end
node_y.parent = node_x.parent
if (node_x.parent == nothing)
tree.root = node_y
##CHUNK 2
end
end
node.parent = node_y
if node_y == nothing
tree.root = node
elseif node.data < node_y.data
node_y.leftChild = node
else
node_y.rightChild = node
end
end
"""
left_rotate!(tree::RBTree, node_x::RBTreeNode)
Performs a left-rotation on `node_x` and updates `tree.root`, if required.
"""
function left_rotate!(tree::RBTree, node_x::RBTreeNode)
node_y = node_x.rightChild
##CHUNK 3
end
end
"""
left_rotate!(tree::RBTree, node_x::RBTreeNode)
Performs a left-rotation on `node_x` and updates `tree.root`, if required.
"""
function left_rotate!(tree::RBTree, node_x::RBTreeNode)
node_y = node_x.rightChild
node_x.rightChild = node_y.leftChild
if node_y.leftChild !== tree.nil
node_y.leftChild.parent = node_x
end
node_y.parent = node_x.parent
if (node_x.parent == nothing)
tree.root = node_y
elseif (node_x == node_x.parent.leftChild)
node_x.parent.leftChild = node_y
else
##CHUNK 4
node_x.rightChild = node_y.leftChild
if node_y.leftChild !== tree.nil
node_y.leftChild.parent = node_x
end
node_y.parent = node_x.parent
if (node_x.parent == nothing)
tree.root = node_y
elseif (node_x == node_x.parent.leftChild)
node_x.parent.leftChild = node_y
else
node_x.parent.rightChild = node_y
end
node_y.leftChild = node_x
node_x.parent = node_y
end
"""
right_rotate!(tree::RBTree, node_x::RBTreeNode)
Performs a right-rotation on `node_x` and updates `tree.root`, if required.
#CURRENT FILE: DataStructures.jl/src/avl_tree.jl
##CHUNK 1
Performs a left-rotation on `node_x`, updates height of the nodes, and returns the rotated node.
"""
"""
right_rotate(node_x::AVLTreeNode)
Performs a right-rotation on `node_x`, updates height of the nodes, and returns the rotated node.
"""
function right_rotate(z::AVLTreeNode)
y = z.leftChild
α = y.rightChild
y.rightChild = z
z.leftChild = α
z.height = compute_height(z)
y.height = compute_height(y)
z.subsize = compute_subtree_size(z)
y.subsize = compute_subtree_size(y)
return y
end
##CHUNK 2
else
L = get_subsize(node.leftChild)
R = get_subsize(node.rightChild)
return (L + R + Int32(1))
end
end
"""
left_rotate(node_x::AVLTreeNode)
Performs a left-rotation on `node_x`, updates height of the nodes, and returns the rotated node.
"""
"""
right_rotate(node_x::AVLTreeNode)
Performs a right-rotation on `node_x`, updates height of the nodes, and returns the rotated node.
"""
function right_rotate(z::AVLTreeNode)
y = z.leftChild
##CHUNK 3
function insert_node(node::AVLTreeNode{K}, key::K) where K
if key < node.data
node.leftChild = insert_node(node.leftChild, key)
else
node.rightChild = insert_node(node.rightChild, key)
end
node.subsize = compute_subtree_size(node)
node.height = compute_height(node)
balance = get_balance(node)
if balance > 1
if key < node.leftChild.data
return right_rotate(node)
else
node.leftChild = left_rotate(node.leftChild)
return right_rotate(node)
end
end
##CHUNK 4
node.height = compute_height(node)
balance = get_balance(node)
if balance > 1
if get_balance(node.leftChild) >= 0
return right_rotate(node)
else
node.leftChild = left_rotate(node.leftChild)
return right_rotate(node)
end
end
if balance < -1
if get_balance(node.rightChild) <= 0
return left_rotate(node)
else
node.rightChild = right_rotate(node.rightChild)
return left_rotate(node)
end
end
##CHUNK 5
α = y.rightChild
y.rightChild = z
z.leftChild = α
z.height = compute_height(z)
y.height = compute_height(y)
z.subsize = compute_subtree_size(z)
y.subsize = compute_subtree_size(y)
return y
end
"""
minimum_node(tree::AVLTree, node::AVLTreeNode)
Returns the AVLTreeNode with minimum value in subtree of `node`.
"""
function minimum_node(node::Union{AVLTreeNode, Nothing})
while node != nothing && node.leftChild != nothing
node = node.leftChild
end
return node
##CHUNK 6
result = node.leftChild
return result
else
result = minimum_node(node.rightChild)
node.data = result.data
node.rightChild = delete_node!(node.rightChild, result.data)
end
end
node.subsize = compute_subtree_size(node)
node.height = compute_height(node)
balance = get_balance(node)
if balance > 1
if get_balance(node.leftChild) >= 0
return right_rotate(node)
else
node.leftChild = left_rotate(node.leftChild)
return right_rotate(node)
end
|
100
| 110
|
DataStructures.jl
| 2
|
function right_rotate(z::AVLTreeNode)
y = z.leftChild
α = y.rightChild
y.rightChild = z
z.leftChild = α
z.height = compute_height(z)
y.height = compute_height(y)
z.subsize = compute_subtree_size(z)
y.subsize = compute_subtree_size(y)
return y
end
|
function right_rotate(z::AVLTreeNode)
y = z.leftChild
α = y.rightChild
y.rightChild = z
z.leftChild = α
z.height = compute_height(z)
y.height = compute_height(y)
z.subsize = compute_subtree_size(z)
y.subsize = compute_subtree_size(y)
return y
end
|
[
100,
110
] |
function right_rotate(z::AVLTreeNode)
y = z.leftChild
α = y.rightChild
y.rightChild = z
z.leftChild = α
z.height = compute_height(z)
y.height = compute_height(y)
z.subsize = compute_subtree_size(z)
y.subsize = compute_subtree_size(y)
return y
end
|
function right_rotate(z::AVLTreeNode)
y = z.leftChild
α = y.rightChild
y.rightChild = z
z.leftChild = α
z.height = compute_height(z)
y.height = compute_height(y)
z.subsize = compute_subtree_size(z)
y.subsize = compute_subtree_size(y)
return y
end
|
right_rotate
| 100
| 110
|
src/avl_tree.jl
|
#FILE: DataStructures.jl/src/red_black_tree.jl
##CHUNK 1
end
end
node.parent = node_y
if node_y == nothing
tree.root = node
elseif node.data < node_y.data
node_y.leftChild = node
else
node_y.rightChild = node
end
end
"""
left_rotate!(tree::RBTree, node_x::RBTreeNode)
Performs a left-rotation on `node_x` and updates `tree.root`, if required.
"""
function left_rotate!(tree::RBTree, node_x::RBTreeNode)
node_y = node_x.rightChild
##CHUNK 2
node_x.parent.rightChild = node_y
end
node_y.leftChild = node_x
node_x.parent = node_y
end
"""
right_rotate!(tree::RBTree, node_x::RBTreeNode)
Performs a right-rotation on `node_x` and updates `tree.root`, if required.
"""
function right_rotate!(tree::RBTree, node_x::RBTreeNode)
node_y = node_x.leftChild
node_x.leftChild = node_y.rightChild
if node_y.rightChild !== tree.nil
node_y.rightChild.parent = node_x
end
node_y.parent = node_x.parent
if (node_x.parent == nothing)
tree.root = node_y
##CHUNK 3
end
end
"""
left_rotate!(tree::RBTree, node_x::RBTreeNode)
Performs a left-rotation on `node_x` and updates `tree.root`, if required.
"""
function left_rotate!(tree::RBTree, node_x::RBTreeNode)
node_y = node_x.rightChild
node_x.rightChild = node_y.leftChild
if node_y.leftChild !== tree.nil
node_y.leftChild.parent = node_x
end
node_y.parent = node_x.parent
if (node_x.parent == nothing)
tree.root = node_y
elseif (node_x == node_x.parent.leftChild)
node_x.parent.leftChild = node_y
else
##CHUNK 4
node_x.rightChild = node_y.leftChild
if node_y.leftChild !== tree.nil
node_y.leftChild.parent = node_x
end
node_y.parent = node_x.parent
if (node_x.parent == nothing)
tree.root = node_y
elseif (node_x == node_x.parent.leftChild)
node_x.parent.leftChild = node_y
else
node_x.parent.rightChild = node_y
end
node_y.leftChild = node_x
node_x.parent = node_y
end
"""
right_rotate!(tree::RBTree, node_x::RBTreeNode)
Performs a right-rotation on `node_x` and updates `tree.root`, if required.
#CURRENT FILE: DataStructures.jl/src/avl_tree.jl
##CHUNK 1
else
L = get_subsize(node.leftChild)
R = get_subsize(node.rightChild)
return (L + R + Int32(1))
end
end
"""
left_rotate(node_x::AVLTreeNode)
Performs a left-rotation on `node_x`, updates height of the nodes, and returns the rotated node.
"""
function left_rotate(z::AVLTreeNode)
y = z.rightChild
α = y.leftChild
y.leftChild = z
z.rightChild = α
z.height = compute_height(z)
y.height = compute_height(y)
z.subsize = compute_subtree_size(z)
##CHUNK 2
Performs a left-rotation on `node_x`, updates height of the nodes, and returns the rotated node.
"""
function left_rotate(z::AVLTreeNode)
y = z.rightChild
α = y.leftChild
y.leftChild = z
z.rightChild = α
z.height = compute_height(z)
y.height = compute_height(y)
z.subsize = compute_subtree_size(z)
y.subsize = compute_subtree_size(y)
return y
end
"""
right_rotate(node_x::AVLTreeNode)
Performs a right-rotation on `node_x`, updates height of the nodes, and returns the rotated node.
"""
##CHUNK 3
function insert_node(node::AVLTreeNode{K}, key::K) where K
if key < node.data
node.leftChild = insert_node(node.leftChild, key)
else
node.rightChild = insert_node(node.rightChild, key)
end
node.subsize = compute_subtree_size(node)
node.height = compute_height(node)
balance = get_balance(node)
if balance > 1
if key < node.leftChild.data
return right_rotate(node)
else
node.leftChild = left_rotate(node.leftChild)
return right_rotate(node)
end
end
##CHUNK 4
node.height = compute_height(node)
balance = get_balance(node)
if balance > 1
if get_balance(node.leftChild) >= 0
return right_rotate(node)
else
node.leftChild = left_rotate(node.leftChild)
return right_rotate(node)
end
end
if balance < -1
if get_balance(node.rightChild) <= 0
return left_rotate(node)
else
node.rightChild = right_rotate(node.rightChild)
return left_rotate(node)
end
end
##CHUNK 5
result = node.leftChild
return result
else
result = minimum_node(node.rightChild)
node.data = result.data
node.rightChild = delete_node!(node.rightChild, result.data)
end
end
node.subsize = compute_subtree_size(node)
node.height = compute_height(node)
balance = get_balance(node)
if balance > 1
if get_balance(node.leftChild) >= 0
return right_rotate(node)
else
node.leftChild = left_rotate(node.leftChild)
return right_rotate(node)
end
##CHUNK 6
# computes the height of the subtree, which basically is
# one added the maximum of the height of the left subtree and right subtree
compute_height(node::AVLTreeNode) = Int8(1) + max(get_height(node.leftChild), get_height(node.rightChild))
get_subsize(node::AVLTreeNode_or_null) = (node == nothing) ? Int32(0) : node.subsize
# compute the subtree size
function compute_subtree_size(node::AVLTreeNode_or_null)
if node == nothing
return Int32(0)
else
L = get_subsize(node.leftChild)
R = get_subsize(node.rightChild)
return (L + R + Int32(1))
end
end
"""
left_rotate(node_x::AVLTreeNode)
|
124
| 138
|
DataStructures.jl
| 3
|
function search_node(tree::AVLTree{K}, d::K) where K
prev = nothing
node = tree.root
while node != nothing && node.data != nothing && node.data != d
prev = node
if d < node.data
node = node.leftChild
else
node = node.rightChild
end
end
return (node == nothing) ? prev : node
end
|
function search_node(tree::AVLTree{K}, d::K) where K
prev = nothing
node = tree.root
while node != nothing && node.data != nothing && node.data != d
prev = node
if d < node.data
node = node.leftChild
else
node = node.rightChild
end
end
return (node == nothing) ? prev : node
end
|
[
124,
138
] |
function search_node(tree::AVLTree{K}, d::K) where K
prev = nothing
node = tree.root
while node != nothing && node.data != nothing && node.data != d
prev = node
if d < node.data
node = node.leftChild
else
node = node.rightChild
end
end
return (node == nothing) ? prev : node
end
|
function search_node(tree::AVLTree{K}, d::K) where K
prev = nothing
node = tree.root
while node != nothing && node.data != nothing && node.data != d
prev = node
if d < node.data
node = node.leftChild
else
node = node.rightChild
end
end
return (node == nothing) ? prev : node
end
|
search_node
| 124
| 138
|
src/avl_tree.jl
|
#FILE: DataStructures.jl/src/splay_tree.jl
##CHUNK 1
x = maximum_node(s)
splay!(tree, x)
x.rightChild = t
t.parent = x
return x
end
end
function search_node(tree::SplayTree{K}, d::K) where K
node = tree.root
prev = nothing
while node != nothing && node.data != d
prev = node
if node.data < d
node = node.rightChild
else
node = node.leftChild
end
end
return (node == nothing) ? prev : node
##CHUNK 2
prev = nothing
while node != nothing && node.data != d
prev = node
if node.data < d
node = node.rightChild
else
node = node.leftChild
end
end
return (node == nothing) ? prev : node
end
function Base.haskey(tree::SplayTree{K}, d::K) where K
node = tree.root
if node === nothing
return false
else
node = search_node(tree, d)
(node === nothing) && return false
is_found = (node.data == d)
##CHUNK 3
node = SplayTreeNode{K}(d)
y = nothing
x = tree.root
while x !== nothing
y = x
if node.data > x.data
x = x.rightChild
else
x = x.leftChild
end
end
node.parent = y
if y === nothing
tree.root = node
elseif node.data < y.data
y.leftChild = node
else
y.rightChild = node
##CHUNK 4
return tree
end
function Base.push!(tree::SplayTree{K}, d0) where K
d = convert(K, d0)
is_present = search_node(tree, d)
if (is_present !== nothing) && (is_present.data == d)
return tree
end
# only unique keys are inserted
node = SplayTreeNode{K}(d)
y = nothing
x = tree.root
while x !== nothing
y = x
if node.data > x.data
x = x.rightChild
else
x = x.leftChild
#FILE: DataStructures.jl/src/red_black_tree.jl
##CHUNK 1
"""
search_node(tree, key)
function search_node(tree::RBTree{K}, d::K) where K
node = tree.root
while node !== tree.nil && d != node.data
if d < node.data
node = node.leftChild
else
node = node.rightChild
end
end
return node
end
"""
haskey(tree, key)
Returns true if `key` is present in the `tree`, else returns false.
"""
##CHUNK 2
function insert_node!(tree::RBTree, node::RBTreeNode)
node_y = nothing
node_x = tree.root
while node_x !== tree.nil
node_y = node_x
if node.data < node_x.data
node_x = node_x.leftChild
else
node_x = node_x.rightChild
end
end
node.parent = node_y
if node_y == nothing
tree.root = node
elseif node.data < node_y.data
node_y.leftChild = node
else
node_y.rightChild = node
##CHUNK 3
end
RBTree() = RBTree{Any}()
Base.length(tree::RBTree) = tree.count
"""
search_node(tree, key)
Returns the last visited node, while traversing through in binary-search-tree fashion looking for `key`.
"""
search_node(tree, key)
function search_node(tree::RBTree{K}, d::K) where K
node = tree.root
while node !== tree.nil && d != node.data
if d < node.data
node = node.leftChild
else
node = node.rightChild
##CHUNK 4
function Base.haskey(tree::RBTree{K}, d::K) where K
node = search_node(tree, d)
return (node.data == d)
end
"""
insert_node!(tree::RBTree, node::RBTreeNode)
Inserts `node` at proper location by traversing through the `tree` in a binary-search-tree fashion.
"""
function insert_node!(tree::RBTree, node::RBTreeNode)
node_y = nothing
node_x = tree.root
while node_x !== tree.nil
node_y = node_x
if node.data < node_x.data
node_x = node_x.leftChild
else
node_x = node_x.rightChild
#CURRENT FILE: DataStructures.jl/src/avl_tree.jl
##CHUNK 1
julia> sorted_rank(tree, 17)
9
```
"""
function sorted_rank(tree::AVLTree{K}, key::K) where K
!haskey(tree, key) && throw(KeyError(key))
node = tree.root
rank = 0
while node.data != key
if (node.data < key)
rank += (1 + get_subsize(node.leftChild))
node = node.rightChild
else
node = node.leftChild
end
end
rank += (1 + get_subsize(node.leftChild))
return rank
end
##CHUNK 2
"""
function Base.push!(tree::AVLTree{K}, key) where K
key0 = convert(K, key)
insert!(tree, key0)
end
function delete_node!(node::AVLTreeNode{K}, key::K) where K
if key < node.data
node.leftChild = delete_node!(node.leftChild, key)
elseif key > node.data
node.rightChild = delete_node!(node.rightChild, key)
else
if node.leftChild == nothing
result = node.rightChild
return result
elseif node.rightChild == nothing
result = node.leftChild
return result
else
result = minimum_node(node.rightChild)
|
162
| 192
|
DataStructures.jl
| 4
|
function insert_node(node::AVLTreeNode{K}, key::K) where K
if key < node.data
node.leftChild = insert_node(node.leftChild, key)
else
node.rightChild = insert_node(node.rightChild, key)
end
node.subsize = compute_subtree_size(node)
node.height = compute_height(node)
balance = get_balance(node)
if balance > 1
if key < node.leftChild.data
return right_rotate(node)
else
node.leftChild = left_rotate(node.leftChild)
return right_rotate(node)
end
end
if balance < -1
if key > node.rightChild.data
return left_rotate(node)
else
node.rightChild = right_rotate(node.rightChild)
return left_rotate(node)
end
end
return node
end
|
function insert_node(node::AVLTreeNode{K}, key::K) where K
if key < node.data
node.leftChild = insert_node(node.leftChild, key)
else
node.rightChild = insert_node(node.rightChild, key)
end
node.subsize = compute_subtree_size(node)
node.height = compute_height(node)
balance = get_balance(node)
if balance > 1
if key < node.leftChild.data
return right_rotate(node)
else
node.leftChild = left_rotate(node.leftChild)
return right_rotate(node)
end
end
if balance < -1
if key > node.rightChild.data
return left_rotate(node)
else
node.rightChild = right_rotate(node.rightChild)
return left_rotate(node)
end
end
return node
end
|
[
162,
192
] |
function insert_node(node::AVLTreeNode{K}, key::K) where K
if key < node.data
node.leftChild = insert_node(node.leftChild, key)
else
node.rightChild = insert_node(node.rightChild, key)
end
node.subsize = compute_subtree_size(node)
node.height = compute_height(node)
balance = get_balance(node)
if balance > 1
if key < node.leftChild.data
return right_rotate(node)
else
node.leftChild = left_rotate(node.leftChild)
return right_rotate(node)
end
end
if balance < -1
if key > node.rightChild.data
return left_rotate(node)
else
node.rightChild = right_rotate(node.rightChild)
return left_rotate(node)
end
end
return node
end
|
function insert_node(node::AVLTreeNode{K}, key::K) where K
if key < node.data
node.leftChild = insert_node(node.leftChild, key)
else
node.rightChild = insert_node(node.rightChild, key)
end
node.subsize = compute_subtree_size(node)
node.height = compute_height(node)
balance = get_balance(node)
if balance > 1
if key < node.leftChild.data
return right_rotate(node)
else
node.leftChild = left_rotate(node.leftChild)
return right_rotate(node)
end
end
if balance < -1
if key > node.rightChild.data
return left_rotate(node)
else
node.rightChild = right_rotate(node.rightChild)
return left_rotate(node)
end
end
return node
end
|
insert_node
| 162
| 192
|
src/avl_tree.jl
|
#FILE: DataStructures.jl/src/red_black_tree.jl
##CHUNK 1
"""
function right_rotate!(tree::RBTree, node_x::RBTreeNode)
node_y = node_x.leftChild
node_x.leftChild = node_y.rightChild
if node_y.rightChild !== tree.nil
node_y.rightChild.parent = node_x
end
node_y.parent = node_x.parent
if (node_x.parent == nothing)
tree.root = node_y
elseif (node_x == node_x.parent.leftChild)
node_x.parent.leftChild = node_y
else
node_x.parent.rightChild = node_y
end
node_y.rightChild = node_x
node_x.parent = node_y
end
"""
##CHUNK 2
end
end
"""
left_rotate!(tree::RBTree, node_x::RBTreeNode)
Performs a left-rotation on `node_x` and updates `tree.root`, if required.
"""
function left_rotate!(tree::RBTree, node_x::RBTreeNode)
node_y = node_x.rightChild
node_x.rightChild = node_y.leftChild
if node_y.leftChild !== tree.nil
node_y.leftChild.parent = node_x
end
node_y.parent = node_x.parent
if (node_x.parent == nothing)
tree.root = node_y
elseif (node_x == node_x.parent.leftChild)
node_x.parent.leftChild = node_y
else
##CHUNK 3
end
end
node.parent = node_y
if node_y == nothing
tree.root = node
elseif node.data < node_y.data
node_y.leftChild = node
else
node_y.rightChild = node
end
end
"""
left_rotate!(tree::RBTree, node_x::RBTreeNode)
Performs a left-rotation on `node_x` and updates `tree.root`, if required.
"""
function left_rotate!(tree::RBTree, node_x::RBTreeNode)
node_y = node_x.rightChild
##CHUNK 4
node_x.rightChild = node_y.leftChild
if node_y.leftChild !== tree.nil
node_y.leftChild.parent = node_x
end
node_y.parent = node_x.parent
if (node_x.parent == nothing)
tree.root = node_y
elseif (node_x == node_x.parent.leftChild)
node_x.parent.leftChild = node_y
else
node_x.parent.rightChild = node_y
end
node_y.leftChild = node_x
node_x.parent = node_y
end
"""
right_rotate!(tree::RBTree, node_x::RBTreeNode)
Performs a right-rotation on `node_x` and updates `tree.root`, if required.
#CURRENT FILE: DataStructures.jl/src/avl_tree.jl
##CHUNK 1
node.height = compute_height(node)
balance = get_balance(node)
if balance > 1
if get_balance(node.leftChild) >= 0
return right_rotate(node)
else
node.leftChild = left_rotate(node.leftChild)
return right_rotate(node)
end
end
if balance < -1
if get_balance(node.rightChild) <= 0
return left_rotate(node)
else
node.rightChild = right_rotate(node.rightChild)
return left_rotate(node)
end
end
##CHUNK 2
result = node.leftChild
return result
else
result = minimum_node(node.rightChild)
node.data = result.data
node.rightChild = delete_node!(node.rightChild, result.data)
end
end
node.subsize = compute_subtree_size(node)
node.height = compute_height(node)
balance = get_balance(node)
if balance > 1
if get_balance(node.leftChild) >= 0
return right_rotate(node)
else
node.leftChild = left_rotate(node.leftChild)
return right_rotate(node)
end
##CHUNK 3
function delete_node!(node::AVLTreeNode{K}, key::K) where K
if key < node.data
node.leftChild = delete_node!(node.leftChild, key)
elseif key > node.data
node.rightChild = delete_node!(node.rightChild, key)
else
if node.leftChild == nothing
result = node.rightChild
return result
elseif node.rightChild == nothing
result = node.leftChild
return result
else
result = minimum_node(node.rightChild)
node.data = result.data
node.rightChild = delete_node!(node.rightChild, result.data)
end
end
node.subsize = compute_subtree_size(node)
##CHUNK 4
"""
push!(tree::AVLTree{K}, key) where K
Insert `key` in AVL tree `tree`.
"""
function Base.push!(tree::AVLTree{K}, key) where K
key0 = convert(K, key)
insert!(tree, key0)
end
function delete_node!(node::AVLTreeNode{K}, key::K) where K
if key < node.data
node.leftChild = delete_node!(node.leftChild, key)
elseif key > node.data
node.rightChild = delete_node!(node.rightChild, key)
else
if node.leftChild == nothing
result = node.rightChild
return result
elseif node.rightChild == nothing
##CHUNK 5
# computes the height of the subtree, which basically is
# one added the maximum of the height of the left subtree and right subtree
compute_height(node::AVLTreeNode) = Int8(1) + max(get_height(node.leftChild), get_height(node.rightChild))
get_subsize(node::AVLTreeNode_or_null) = (node == nothing) ? Int32(0) : node.subsize
# compute the subtree size
function compute_subtree_size(node::AVLTreeNode_or_null)
if node == nothing
return Int32(0)
else
L = get_subsize(node.leftChild)
R = get_subsize(node.rightChild)
return (L + R + Int32(1))
end
end
"""
left_rotate(node_x::AVLTreeNode)
##CHUNK 6
else
L = get_subsize(node.leftChild)
R = get_subsize(node.rightChild)
return (L + R + Int32(1))
end
end
"""
left_rotate(node_x::AVLTreeNode)
Performs a left-rotation on `node_x`, updates height of the nodes, and returns the rotated node.
"""
function left_rotate(z::AVLTreeNode)
y = z.rightChild
α = y.leftChild
y.leftChild = z
z.rightChild = α
z.height = compute_height(z)
y.height = compute_height(y)
z.subsize = compute_subtree_size(z)
|
212
| 254
|
DataStructures.jl
| 5
|
function delete_node!(node::AVLTreeNode{K}, key::K) where K
if key < node.data
node.leftChild = delete_node!(node.leftChild, key)
elseif key > node.data
node.rightChild = delete_node!(node.rightChild, key)
else
if node.leftChild == nothing
result = node.rightChild
return result
elseif node.rightChild == nothing
result = node.leftChild
return result
else
result = minimum_node(node.rightChild)
node.data = result.data
node.rightChild = delete_node!(node.rightChild, result.data)
end
end
node.subsize = compute_subtree_size(node)
node.height = compute_height(node)
balance = get_balance(node)
if balance > 1
if get_balance(node.leftChild) >= 0
return right_rotate(node)
else
node.leftChild = left_rotate(node.leftChild)
return right_rotate(node)
end
end
if balance < -1
if get_balance(node.rightChild) <= 0
return left_rotate(node)
else
node.rightChild = right_rotate(node.rightChild)
return left_rotate(node)
end
end
return node
end
|
function delete_node!(node::AVLTreeNode{K}, key::K) where K
if key < node.data
node.leftChild = delete_node!(node.leftChild, key)
elseif key > node.data
node.rightChild = delete_node!(node.rightChild, key)
else
if node.leftChild == nothing
result = node.rightChild
return result
elseif node.rightChild == nothing
result = node.leftChild
return result
else
result = minimum_node(node.rightChild)
node.data = result.data
node.rightChild = delete_node!(node.rightChild, result.data)
end
end
node.subsize = compute_subtree_size(node)
node.height = compute_height(node)
balance = get_balance(node)
if balance > 1
if get_balance(node.leftChild) >= 0
return right_rotate(node)
else
node.leftChild = left_rotate(node.leftChild)
return right_rotate(node)
end
end
if balance < -1
if get_balance(node.rightChild) <= 0
return left_rotate(node)
else
node.rightChild = right_rotate(node.rightChild)
return left_rotate(node)
end
end
return node
end
|
[
212,
254
] |
function delete_node!(node::AVLTreeNode{K}, key::K) where K
if key < node.data
node.leftChild = delete_node!(node.leftChild, key)
elseif key > node.data
node.rightChild = delete_node!(node.rightChild, key)
else
if node.leftChild == nothing
result = node.rightChild
return result
elseif node.rightChild == nothing
result = node.leftChild
return result
else
result = minimum_node(node.rightChild)
node.data = result.data
node.rightChild = delete_node!(node.rightChild, result.data)
end
end
node.subsize = compute_subtree_size(node)
node.height = compute_height(node)
balance = get_balance(node)
if balance > 1
if get_balance(node.leftChild) >= 0
return right_rotate(node)
else
node.leftChild = left_rotate(node.leftChild)
return right_rotate(node)
end
end
if balance < -1
if get_balance(node.rightChild) <= 0
return left_rotate(node)
else
node.rightChild = right_rotate(node.rightChild)
return left_rotate(node)
end
end
return node
end
|
function delete_node!(node::AVLTreeNode{K}, key::K) where K
if key < node.data
node.leftChild = delete_node!(node.leftChild, key)
elseif key > node.data
node.rightChild = delete_node!(node.rightChild, key)
else
if node.leftChild == nothing
result = node.rightChild
return result
elseif node.rightChild == nothing
result = node.leftChild
return result
else
result = minimum_node(node.rightChild)
node.data = result.data
node.rightChild = delete_node!(node.rightChild, result.data)
end
end
node.subsize = compute_subtree_size(node)
node.height = compute_height(node)
balance = get_balance(node)
if balance > 1
if get_balance(node.leftChild) >= 0
return right_rotate(node)
else
node.leftChild = left_rotate(node.leftChild)
return right_rotate(node)
end
end
if balance < -1
if get_balance(node.rightChild) <= 0
return left_rotate(node)
else
node.rightChild = right_rotate(node.rightChild)
return left_rotate(node)
end
end
return node
end
|
delete_node!
| 212
| 254
|
src/avl_tree.jl
|
#FILE: DataStructures.jl/src/splay_tree.jl
##CHUNK 1
# double rotation
elseif node_x == parent.leftChild && parent == grand_parent.leftChild
# zig-zig rotation
right_rotate!(tree, grand_parent)
right_rotate!(tree, parent)
elseif node_x == parent.rightChild && parent == grand_parent.rightChild
# zag-zag rotation
left_rotate!(tree, grand_parent)
left_rotate!(tree, parent)
elseif node_x == parent.rightChild && parent == grand_parent.leftChild
# zig-zag rotation
left_rotate!(tree, node_x.parent)
right_rotate!(tree, node_x.parent)
else
# zag-zig rotation
right_rotate!(tree, node_x.parent)
left_rotate!(tree, node_x.parent)
end
end
end
#FILE: DataStructures.jl/src/red_black_tree.jl
##CHUNK 1
"""
function right_rotate!(tree::RBTree, node_x::RBTreeNode)
node_y = node_x.leftChild
node_x.leftChild = node_y.rightChild
if node_y.rightChild !== tree.nil
node_y.rightChild.parent = node_x
end
node_y.parent = node_x.parent
if (node_x.parent == nothing)
tree.root = node_y
elseif (node_x == node_x.parent.leftChild)
node_x.parent.leftChild = node_y
else
node_x.parent.rightChild = node_y
end
node_y.rightChild = node_x
node_x.parent = node_y
end
"""
##CHUNK 2
else # uncle is black in color
if (node == parent.leftChild) # node is leftChild of its parent
node = parent
right_rotate!(tree, node)
end
# node is rightChild of its parent
node.parent.color = false
node.parent.parent.color = true
left_rotate!(tree, node.parent.parent)
end
end
end
tree.root.color = false
end
"""
insert!(tree, key)
Inserts `key` in the `tree` if it is not present.
"""
##CHUNK 3
end
"""
minimum_node(tree::RBTree, node::RBTreeNode)
Returns the RBTreeNode with minimum value in subtree of `node`.
"""
function minimum_node(tree::RBTree, node::RBTreeNode)
(node === tree.nil) && return node
while node.leftChild !== tree.nil
node = node.leftChild
end
return node
end
"""
delete!(tree::RBTree, key)
Deletes `key` from `tree`, if present, else returns the unmodified tree.
"""
##CHUNK 4
end
end
"""
left_rotate!(tree::RBTree, node_x::RBTreeNode)
Performs a left-rotation on `node_x` and updates `tree.root`, if required.
"""
function left_rotate!(tree::RBTree, node_x::RBTreeNode)
node_y = node_x.rightChild
node_x.rightChild = node_y.leftChild
if node_y.leftChild !== tree.nil
node_y.leftChild.parent = node_x
end
node_y.parent = node_x.parent
if (node_x.parent == nothing)
tree.root = node_y
elseif (node_x == node_x.parent.leftChild)
node_x.parent.leftChild = node_y
else
##CHUNK 5
node_x.rightChild = node_y.leftChild
if node_y.leftChild !== tree.nil
node_y.leftChild.parent = node_x
end
node_y.parent = node_x.parent
if (node_x.parent == nothing)
tree.root = node_y
elseif (node_x == node_x.parent.leftChild)
node_x.parent.leftChild = node_y
else
node_x.parent.rightChild = node_y
end
node_y.leftChild = node_x
node_x.parent = node_y
end
"""
right_rotate!(tree::RBTree, node_x::RBTreeNode)
Performs a right-rotation on `node_x` and updates `tree.root`, if required.
#FILE: DataStructures.jl/src/balanced_tree.jl
##CHUNK 1
end
@inbounds thisnode = t.tree[curnode]
cmp = thisnode.child3 == 0 ?
cmp2le_leaf(t.ord, thisnode, k) :
cmp3le_leaf(t.ord, thisnode, k)
curnode = cmp == 1 ? thisnode.child1 :
cmp == 2 ? thisnode.child2 : thisnode.child3
return curnode
end
## The following are helper routines for the insert! and delete! functions.
## They replace the 'parent' field of either an internal tree node or
## a data node at the bottom tree level.
function replaceparent!(data::Vector{KDRec{K,D}}, whichind::Int, newparent::Int) where {K,D}
data[whichind] = KDRec{K,D}(newparent, data[whichind].k, data[whichind].d)
return nothing
end
#CURRENT FILE: DataStructures.jl/src/avl_tree.jl
##CHUNK 1
balance = get_balance(node)
if balance > 1
if key < node.leftChild.data
return right_rotate(node)
else
node.leftChild = left_rotate(node.leftChild)
return right_rotate(node)
end
end
if balance < -1
if key > node.rightChild.data
return left_rotate(node)
else
node.rightChild = right_rotate(node.rightChild)
return left_rotate(node)
end
end
##CHUNK 2
if balance < -1
if key > node.rightChild.data
return left_rotate(node)
else
node.rightChild = right_rotate(node.rightChild)
return left_rotate(node)
end
end
return node
end
function Base.insert!(tree::AVLTree{K}, d::K) where K
haskey(tree, d) && return tree
tree.root = insert_node(tree.root, d)
tree.count += 1
return tree
end
##CHUNK 3
# computes the height of the subtree, which basically is
# one added the maximum of the height of the left subtree and right subtree
compute_height(node::AVLTreeNode) = Int8(1) + max(get_height(node.leftChild), get_height(node.rightChild))
get_subsize(node::AVLTreeNode_or_null) = (node == nothing) ? Int32(0) : node.subsize
# compute the subtree size
function compute_subtree_size(node::AVLTreeNode_or_null)
if node == nothing
return Int32(0)
else
L = get_subsize(node.leftChild)
R = get_subsize(node.rightChild)
return (L + R + Int32(1))
end
end
"""
left_rotate(node_x::AVLTreeNode)
|
290
| 304
|
DataStructures.jl
| 6
|
function sorted_rank(tree::AVLTree{K}, key::K) where K
!haskey(tree, key) && throw(KeyError(key))
node = tree.root
rank = 0
while node.data != key
if (node.data < key)
rank += (1 + get_subsize(node.leftChild))
node = node.rightChild
else
node = node.leftChild
end
end
rank += (1 + get_subsize(node.leftChild))
return rank
end
|
function sorted_rank(tree::AVLTree{K}, key::K) where K
!haskey(tree, key) && throw(KeyError(key))
node = tree.root
rank = 0
while node.data != key
if (node.data < key)
rank += (1 + get_subsize(node.leftChild))
node = node.rightChild
else
node = node.leftChild
end
end
rank += (1 + get_subsize(node.leftChild))
return rank
end
|
[
290,
304
] |
function sorted_rank(tree::AVLTree{K}, key::K) where K
!haskey(tree, key) && throw(KeyError(key))
node = tree.root
rank = 0
while node.data != key
if (node.data < key)
rank += (1 + get_subsize(node.leftChild))
node = node.rightChild
else
node = node.leftChild
end
end
rank += (1 + get_subsize(node.leftChild))
return rank
end
|
function sorted_rank(tree::AVLTree{K}, key::K) where K
!haskey(tree, key) && throw(KeyError(key))
node = tree.root
rank = 0
while node.data != key
if (node.data < key)
rank += (1 + get_subsize(node.leftChild))
node = node.rightChild
else
node = node.leftChild
end
end
rank += (1 + get_subsize(node.leftChild))
return rank
end
|
sorted_rank
| 290
| 304
|
src/avl_tree.jl
|
#FILE: DataStructures.jl/src/red_black_tree.jl
##CHUNK 1
"""
search_node(tree, key)
function search_node(tree::RBTree{K}, d::K) where K
node = tree.root
while node !== tree.nil && d != node.data
if d < node.data
node = node.leftChild
else
node = node.rightChild
end
end
return node
end
"""
haskey(tree, key)
Returns true if `key` is present in the `tree`, else returns false.
"""
##CHUNK 2
end
RBTree() = RBTree{Any}()
Base.length(tree::RBTree) = tree.count
"""
search_node(tree, key)
Returns the last visited node, while traversing through in binary-search-tree fashion looking for `key`.
"""
search_node(tree, key)
function search_node(tree::RBTree{K}, d::K) where K
node = tree.root
while node !== tree.nil && d != node.data
if d < node.data
node = node.leftChild
else
node = node.rightChild
##CHUNK 3
function Base.haskey(tree::RBTree{K}, d::K) where K
node = search_node(tree, d)
return (node.data == d)
end
"""
insert_node!(tree::RBTree, node::RBTreeNode)
Inserts `node` at proper location by traversing through the `tree` in a binary-search-tree fashion.
"""
function insert_node!(tree::RBTree, node::RBTreeNode)
node_y = nothing
node_x = tree.root
while node_x !== tree.nil
node_y = node_x
if node.data < node_x.data
node_x = node_x.leftChild
else
node_x = node_x.rightChild
#FILE: DataStructures.jl/src/splay_tree.jl
##CHUNK 1
node = SplayTreeNode{K}(d)
y = nothing
x = tree.root
while x !== nothing
y = x
if node.data > x.data
x = x.rightChild
else
x = x.leftChild
end
end
node.parent = y
if y === nothing
tree.root = node
elseif node.data < y.data
y.leftChild = node
else
y.rightChild = node
#CURRENT FILE: DataStructures.jl/src/avl_tree.jl
##CHUNK 1
if balance < -1
if key > node.rightChild.data
return left_rotate(node)
else
node.rightChild = right_rotate(node.rightChild)
return left_rotate(node)
end
end
return node
end
function Base.insert!(tree::AVLTree{K}, d::K) where K
haskey(tree, d) && return tree
tree.root = insert_node(tree.root, d)
tree.count += 1
return tree
end
##CHUNK 2
"""
push!(tree::AVLTree{K}, key) where K
Insert `key` in AVL tree `tree`.
"""
function Base.push!(tree::AVLTree{K}, key) where K
key0 = convert(K, key)
insert!(tree, key0)
end
function delete_node!(node::AVLTreeNode{K}, key::K) where K
if key < node.data
node.leftChild = delete_node!(node.leftChild, key)
elseif key > node.data
node.rightChild = delete_node!(node.rightChild, key)
else
if node.leftChild == nothing
result = node.rightChild
return result
##CHUNK 3
function insert_node(node::AVLTreeNode{K}, key::K) where K
if key < node.data
node.leftChild = insert_node(node.leftChild, key)
else
node.rightChild = insert_node(node.rightChild, key)
end
node.subsize = compute_subtree_size(node)
node.height = compute_height(node)
balance = get_balance(node)
if balance > 1
if key < node.leftChild.data
return right_rotate(node)
else
node.leftChild = left_rotate(node.leftChild)
return right_rotate(node)
end
end
##CHUNK 4
return node
end
function search_node(tree::AVLTree{K}, d::K) where K
prev = nothing
node = tree.root
while node != nothing && node.data != nothing && node.data != d
prev = node
if d < node.data
node = node.leftChild
else
node = node.rightChild
end
end
return (node == nothing) ? prev : node
end
"""
##CHUNK 5
function Base.delete!(tree::AVLTree{K}, k::K) where K
# if the key is not in the tree, do nothing and return the tree
!haskey(tree, k) && return tree
# if the key is present, delete it from the tree
tree.root = delete_node!(tree.root, k)
tree.count -= 1
return tree
end
"""
sorted_rank(tree::AVLTree{K}, key::K) where K
Returns the rank of `key` present in the `tree`, if it present. A `KeyError` is thrown if `key`
is not present.
# Examples
```jldoctest
julia> tree = AVLTree{Int}();
##CHUNK 6
function delete_node!(node::AVLTreeNode{K}, key::K) where K
if key < node.data
node.leftChild = delete_node!(node.leftChild, key)
elseif key > node.data
node.rightChild = delete_node!(node.rightChild, key)
else
if node.leftChild == nothing
result = node.rightChild
return result
elseif node.rightChild == nothing
result = node.leftChild
return result
else
result = minimum_node(node.rightChild)
node.data = result.data
node.rightChild = delete_node!(node.rightChild, result.data)
end
end
|
329
| 345
|
DataStructures.jl
| 7
|
function Base.getindex(tree::AVLTree{K}, ind::Integer) where K
@boundscheck (1 <= ind <= tree.count) || throw(BoundsError("$ind should be in between 1 and $(tree.count)"))
function traverse_tree(node::AVLTreeNode_or_null, idx)
if (node != nothing)
L = get_subsize(node.leftChild)
if idx <= L
return traverse_tree(node.leftChild, idx)
elseif idx == L + 1
return node.data
else
return traverse_tree(node.rightChild, idx - L - 1)
end
end
end
value = traverse_tree(tree.root, ind)
return value
end
|
function Base.getindex(tree::AVLTree{K}, ind::Integer) where K
@boundscheck (1 <= ind <= tree.count) || throw(BoundsError("$ind should be in between 1 and $(tree.count)"))
function traverse_tree(node::AVLTreeNode_or_null, idx)
if (node != nothing)
L = get_subsize(node.leftChild)
if idx <= L
return traverse_tree(node.leftChild, idx)
elseif idx == L + 1
return node.data
else
return traverse_tree(node.rightChild, idx - L - 1)
end
end
end
value = traverse_tree(tree.root, ind)
return value
end
|
[
329,
345
] |
function Base.getindex(tree::AVLTree{K}, ind::Integer) where K
@boundscheck (1 <= ind <= tree.count) || throw(BoundsError("$ind should be in between 1 and $(tree.count)"))
function traverse_tree(node::AVLTreeNode_or_null, idx)
if (node != nothing)
L = get_subsize(node.leftChild)
if idx <= L
return traverse_tree(node.leftChild, idx)
elseif idx == L + 1
return node.data
else
return traverse_tree(node.rightChild, idx - L - 1)
end
end
end
value = traverse_tree(tree.root, ind)
return value
end
|
function Base.getindex(tree::AVLTree{K}, ind::Integer) where K
@boundscheck (1 <= ind <= tree.count) || throw(BoundsError("$ind should be in between 1 and $(tree.count)"))
function traverse_tree(node::AVLTreeNode_or_null, idx)
if (node != nothing)
L = get_subsize(node.leftChild)
if idx <= L
return traverse_tree(node.leftChild, idx)
elseif idx == L + 1
return node.data
else
return traverse_tree(node.rightChild, idx - L - 1)
end
end
end
value = traverse_tree(tree.root, ind)
return value
end
|
traverse_tree
| 329
| 345
|
src/avl_tree.jl
|
#FILE: DataStructures.jl/src/red_black_tree.jl
##CHUNK 1
Base.in(key, tree::RBTree) = haskey(tree, key)
"""
getindex(tree, ind)
Gets the key present at index `ind` of the tree. Indexing is done in increasing order of key.
"""
function Base.getindex(tree::RBTree{K}, ind) where K
@boundscheck (1 <= ind <= tree.count) || throw(ArgumentError("$ind should be in between 1 and $(tree.count)"))
function traverse_tree_inorder(node::RBTreeNode{K}) where K
if (node !== tree.nil)
left = traverse_tree_inorder(node.leftChild)
right = traverse_tree_inorder(node.rightChild)
append!(push!(left, node.data), right)
else
return K[]
end
end
arr = traverse_tree_inorder(tree.root)
##CHUNK 2
rb_transplant(tree, z, y)
y.leftChild = z.leftChild
y.leftChild.parent = y
y.color = z.color
end
!y_original_color && delete_fix(tree, x)
tree.count -= 1
return tree
end
Base.in(key, tree::RBTree) = haskey(tree, key)
"""
getindex(tree, ind)
Gets the key present at index `ind` of the tree. Indexing is done in increasing order of key.
"""
function Base.getindex(tree::RBTree{K}, ind) where K
@boundscheck (1 <= ind <= tree.count) || throw(ArgumentError("$ind should be in between 1 and $(tree.count)"))
##CHUNK 3
"""
search_node(tree, key)
function search_node(tree::RBTree{K}, d::K) where K
node = tree.root
while node !== tree.nil && d != node.data
if d < node.data
node = node.leftChild
else
node = node.rightChild
end
end
return node
end
"""
haskey(tree, key)
Returns true if `key` is present in the `tree`, else returns false.
"""
##CHUNK 4
end
RBTree() = RBTree{Any}()
Base.length(tree::RBTree) = tree.count
"""
search_node(tree, key)
Returns the last visited node, while traversing through in binary-search-tree fashion looking for `key`.
"""
search_node(tree, key)
function search_node(tree::RBTree{K}, d::K) where K
node = tree.root
while node !== tree.nil && d != node.data
if d < node.data
node = node.leftChild
else
node = node.rightChild
##CHUNK 5
function traverse_tree_inorder(node::RBTreeNode{K}) where K
if (node !== tree.nil)
left = traverse_tree_inorder(node.leftChild)
right = traverse_tree_inorder(node.rightChild)
append!(push!(left, node.data), right)
else
return K[]
end
end
arr = traverse_tree_inorder(tree.root)
return @inbounds arr[ind]
end
#FILE: DataStructures.jl/src/splay_tree.jl
##CHUNK 1
end
splay!(tree, node)
tree.count += 1
return tree
end
function Base.getindex(tree::SplayTree{K}, ind) where K
@boundscheck (1 <= ind <= tree.count) || throw(KeyError("$ind should be in between 1 and $(tree.count)"))
function traverse_tree_inorder(node::Union{SplayTreeNode, Nothing})
if (node != nothing)
left = traverse_tree_inorder(node.leftChild)
right = traverse_tree_inorder(node.rightChild)
append!(push!(left, node.data), right)
else
return K[]
end
end
arr = traverse_tree_inorder(tree.root)
return @inbounds arr[ind]
end
##CHUNK 2
end
end
node.parent = y
if y === nothing
tree.root = node
elseif node.data < y.data
y.leftChild = node
else
y.rightChild = node
end
splay!(tree, node)
tree.count += 1
return tree
end
function Base.getindex(tree::SplayTree{K}, ind) where K
@boundscheck (1 <= ind <= tree.count) || throw(KeyError("$ind should be in between 1 and $(tree.count)"))
function traverse_tree_inorder(node::Union{SplayTreeNode, Nothing})
if (node != nothing)
#CURRENT FILE: DataStructures.jl/src/avl_tree.jl
##CHUNK 1
!haskey(tree, key) && throw(KeyError(key))
node = tree.root
rank = 0
while node.data != key
if (node.data < key)
rank += (1 + get_subsize(node.leftChild))
node = node.rightChild
else
node = node.leftChild
end
end
rank += (1 + get_subsize(node.leftChild))
return rank
end
"""
getindex(tree::AVLTree{K}, ind::Integer) where K
Considering the elements of `tree` sorted, returns the `ind`-th element in `tree`. Search
operation is performed in \$O(\\log n)\$ time complexity.
##CHUNK 2
return node
end
function search_node(tree::AVLTree{K}, d::K) where K
prev = nothing
node = tree.root
while node != nothing && node.data != nothing && node.data != d
prev = node
if d < node.data
node = node.leftChild
else
node = node.rightChild
end
end
return (node == nothing) ? prev : node
end
"""
##CHUNK 3
"""
push!(tree::AVLTree{K}, key) where K
Insert `key` in AVL tree `tree`.
"""
function Base.push!(tree::AVLTree{K}, key) where K
key0 = convert(K, key)
insert!(tree, key0)
end
function delete_node!(node::AVLTreeNode{K}, key::K) where K
if key < node.data
node.leftChild = delete_node!(node.leftChild, key)
elseif key > node.data
node.rightChild = delete_node!(node.rightChild, key)
else
if node.leftChild == nothing
result = node.rightChild
return result
|
238
| 250
|
DataStructures.jl
| 8
|
function Base.empty!(t::BalancedTree23)
resize!(t.data,2)
initializeData!(t.data)
resize!(t.tree,1)
initializeTree!(t.tree)
t.depth = 1
t.rootloc = 1
empty!(t.freetreeinds)
empty!(t.freedatainds)
empty!(t.useddatacells)
push!(t.useddatacells, 1, 2)
return nothing
end
|
function Base.empty!(t::BalancedTree23)
resize!(t.data,2)
initializeData!(t.data)
resize!(t.tree,1)
initializeTree!(t.tree)
t.depth = 1
t.rootloc = 1
empty!(t.freetreeinds)
empty!(t.freedatainds)
empty!(t.useddatacells)
push!(t.useddatacells, 1, 2)
return nothing
end
|
[
238,
250
] |
function Base.empty!(t::BalancedTree23)
resize!(t.data,2)
initializeData!(t.data)
resize!(t.tree,1)
initializeTree!(t.tree)
t.depth = 1
t.rootloc = 1
empty!(t.freetreeinds)
empty!(t.freedatainds)
empty!(t.useddatacells)
push!(t.useddatacells, 1, 2)
return nothing
end
|
function Base.empty!(t::BalancedTree23)
resize!(t.data,2)
initializeData!(t.data)
resize!(t.tree,1)
initializeTree!(t.tree)
t.depth = 1
t.rootloc = 1
empty!(t.freetreeinds)
empty!(t.freedatainds)
empty!(t.useddatacells)
push!(t.useddatacells, 1, 2)
return nothing
end
|
Base.empty!
| 238
| 250
|
src/balanced_tree.jl
|
#FILE: DataStructures.jl/test/test_sorted_containers.jl
##CHUNK 1
end
remove_spaces(s::String) = replace(s, r"\s+"=>"")
## Function checkcorrectness checks a balanced tree for correctness.
function checkcorrectness(t::DataStructures.BalancedTree23{K,D,Ord},
allowdups=false) where {K,D,Ord <: Ordering}
dsz = size(t.data, 1)
tsz = size(t.tree, 1)
r = t.rootloc
bfstreenodes = Vector{Int}()
tdpth = t.depth
intree = BitSet()
levstart = Vector{Int}(undef, tdpth)
push!(bfstreenodes, r)
levstart[1] = 1
##CHUNK 2
throw(ErrorException("t.useddatacells has indices larger than t.data size"))
end
for i = 1 : dsz
if (in(i, dataused) && !in(i, t.useddatacells)) ||
(!in(i,dataused) && in(i, t.useddatacells))
throw(ErrorException("Mismatch between actual data cells used and useddatacells array"))
end
if (in(i, freedata) && in(i, dataused)) ||
(!in(i,freedata) && !in(i, dataused))
throw(ErrorException("Mismatch between t.freedatainds and t.useddatacells"))
end
end
freetree = BitSet()
for i = 1 : size(t.freetreeinds,1)
tfi = t.freetreeinds[i]
if in(tfi, freetree)
throw(ErrorException("Free tree index repeated twice"))
end
if tfi < 1 || tfi > tsz
throw(ErrorException("Free tree index out of range"))
#CURRENT FILE: DataStructures.jl/src/balanced_tree.jl
##CHUNK 1
mutable struct BalancedTree23{K, D, Ord <: Ordering}
ord::Ord
data::Vector{KDRec{K,D}}
tree::Vector{TreeNode{K}}
rootloc::Int
depth::Int
freetreeinds::Vector{Int}
freedatainds::Vector{Int}
useddatacells::BitSet
# The next two arrays are used as a workspace by the delete!
# function.
deletionchild::Vector{Int}
deletionleftkey::Vector{K}
function BalancedTree23{K,D,Ord}(ord1::Ord) where {K,D,Ord<:Ordering}
tree1 = Vector{TreeNode{K}}(undef, 1)
initializeTree!(tree1)
data1 = Vector{KDRec{K,D}}(undef, 2)
initializeData!(data1)
u1 = BitSet()
push!(u1, 1, 2)
##CHUNK 2
if exactfound && !allowdups
t.data[leafind] = KDRec{K,D}(parent, k,d)
return false, leafind
end
# We get here if k was not already found in the tree or
# if duplicates are allowed.
# In this case we insert a new node.
depth = t.depth
ord = t.ord
## Store the new data item in the tree's data array. Later
## go back and fix the parent.
newind = push_or_reuse!(t.data, t.freedatainds, KDRec{K,D}(0,k,d))
push!(t.useddatacells, newind)
p1 = parent
newchild = newind
minkeynewchild = k
splitroot = false
##CHUNK 3
t.tree[rightsib].splitkey1)
if curdepth == t.depth
replaceparent!(t.data, rc1, p)
replaceparent!(t.data, rc2, p)
else
replaceparent!(t.tree, rc1, p)
replaceparent!(t.tree, rc2, p)
end
push!(t.freetreeinds, rightsib)
newchildcount = 1
t.deletionchild[1] = p
else
rc1 = t.tree[rightsib].child1
t.tree[p] = TreeNode{K}(t.deletionchild[1], rc1, 0,
pparent,
t.tree[pparent].splitkey1,
defaultKey)
sk1 = t.tree[rightsib].splitkey1
t.tree[rightsib] = TreeNode{K}(t.tree[rightsib].child2,
t.tree[rightsib].child3,
##CHUNK 4
# if newchild4==0
if newchild4 == 0
# Change the parent from a 2-node to a 3-node
t.tree[p1] = TreeNode{K}(newchild1, newchild2, newchild3,
p1parent, minkeychild2, minkeychild3)
if curdepth == depth
replaceparent!(t.data, newchild, p1)
else
replaceparent!(t.tree, newchild, p1)
end
break
end
# Split the parent
t.tree[p1] = TreeNode{K}(newchild1, newchild2, 0,
p1parent, minkeychild2, minkeychild2)
newtreenode = TreeNode{K}(newchild3, newchild4, 0,
p1parent, minkeychild4, minkeychild2)
newparentnum = push_or_reuse!(t.tree, t.freetreeinds, newtreenode)
if curdepth == depth
##CHUNK 5
t.deletionchild[newchildcount] = c1
t.deletionleftkey[newchildcount] = t.data[c1].k
end
c2 = t.tree[p].child2
if c2 != it
newchildcount += 1
t.deletionchild[newchildcount] = c2
t.deletionleftkey[newchildcount] = t.data[c2].k
end
c3 = t.tree[p].child3
if c3 != it && c3 > 0
newchildcount += 1
t.deletionchild[newchildcount] = c3
t.deletionleftkey[newchildcount] = t.data[c3].k
end
@invariant newchildcount == 1 || newchildcount == 2
push!(t.freedatainds, it)
pop!(t.useddatacells,it)
defaultKey = t.tree[1].splitkey1
curdepth = t.depth
##CHUNK 6
## tree array (locations are freed due to deletion)
## freedatainds: Array of indices of free locations in the
## data array (locations are freed due to deletion)
## useddatacells: BitSet (i.e., bit vector) showing which
## data cells are taken. The complementary positions are
## exactly those stored in freedatainds. This array is
## used only for error checking.
## deletionchild and deletionleftkey are two work-arrays
## for the delete function.
mutable struct BalancedTree23{K, D, Ord <: Ordering}
ord::Ord
data::Vector{KDRec{K,D}}
tree::Vector{TreeNode{K}}
rootloc::Int
depth::Int
freetreeinds::Vector{Int}
freedatainds::Vector{Int}
useddatacells::BitSet
# The next two arrays are used as a workspace by the delete!
##CHUNK 7
lk)
if curdepth == t.depth
replaceparent!(t.data, lc1, p)
replaceparent!(t.data, lc2, p)
else
replaceparent!(t.tree, lc1, p)
replaceparent!(t.tree, lc2, p)
end
push!(t.freetreeinds, leftsib)
newchildcount = 2
t.deletionchild[1] = t.tree[pparent].child1
t.deletionleftkey[2] = t.tree[pparent].splitkey1
t.deletionchild[2] = p
else
lc3 = t.tree[leftsib].child3
t.tree[p] = TreeNode{K}(lc3, t.deletionchild[1], 0,
pparent, lk, defaultKey)
sk2 = t.tree[leftsib].splitkey2
t.tree[leftsib] = TreeNode{K}(t.tree[leftsib].child1,
t.tree[leftsib].child2,
##CHUNK 8
else
replaceparent!(t.tree, lc1, p)
replaceparent!(t.tree, lc2, p)
end
push!(t.freetreeinds, leftsib)
newchildcount = 1
t.deletionchild[1] = p
else
lc3 = t.tree[leftsib].child3
t.tree[p] = TreeNode{K}(lc3, t.deletionchild[1], 0,
pparent, lk, defaultKey)
sk2 = t.tree[leftsib].splitkey2
t.tree[leftsib] = TreeNode{K}(t.tree[leftsib].child1,
t.tree[leftsib].child2,
0, pparent,
t.tree[leftsib].splitkey1,
defaultKey)
if curdepth == t.depth
replaceparent!(t.data, lc3, p)
else
|
292
| 309
|
DataStructures.jl
| 9
|
function findkeyless(t::BalancedTree23, k)
curnode = t.rootloc
for depthcount = 1 : t.depth - 1
@inbounds thisnode = t.tree[curnode]
cmp = thisnode.child3 == 0 ?
cmp2le_nonleaf(t.ord, thisnode, k) :
cmp3le_nonleaf(t.ord, thisnode, k)
curnode = cmp == 1 ? thisnode.child1 :
cmp == 2 ? thisnode.child2 : thisnode.child3
end
@inbounds thisnode = t.tree[curnode]
cmp = thisnode.child3 == 0 ?
cmp2le_leaf(t.ord, thisnode, k) :
cmp3le_leaf(t.ord, thisnode, k)
curnode = cmp == 1 ? thisnode.child1 :
cmp == 2 ? thisnode.child2 : thisnode.child3
return curnode
end
|
function findkeyless(t::BalancedTree23, k)
curnode = t.rootloc
for depthcount = 1 : t.depth - 1
@inbounds thisnode = t.tree[curnode]
cmp = thisnode.child3 == 0 ?
cmp2le_nonleaf(t.ord, thisnode, k) :
cmp3le_nonleaf(t.ord, thisnode, k)
curnode = cmp == 1 ? thisnode.child1 :
cmp == 2 ? thisnode.child2 : thisnode.child3
end
@inbounds thisnode = t.tree[curnode]
cmp = thisnode.child3 == 0 ?
cmp2le_leaf(t.ord, thisnode, k) :
cmp3le_leaf(t.ord, thisnode, k)
curnode = cmp == 1 ? thisnode.child1 :
cmp == 2 ? thisnode.child2 : thisnode.child3
return curnode
end
|
[
292,
309
] |
function findkeyless(t::BalancedTree23, k)
curnode = t.rootloc
for depthcount = 1 : t.depth - 1
@inbounds thisnode = t.tree[curnode]
cmp = thisnode.child3 == 0 ?
cmp2le_nonleaf(t.ord, thisnode, k) :
cmp3le_nonleaf(t.ord, thisnode, k)
curnode = cmp == 1 ? thisnode.child1 :
cmp == 2 ? thisnode.child2 : thisnode.child3
end
@inbounds thisnode = t.tree[curnode]
cmp = thisnode.child3 == 0 ?
cmp2le_leaf(t.ord, thisnode, k) :
cmp3le_leaf(t.ord, thisnode, k)
curnode = cmp == 1 ? thisnode.child1 :
cmp == 2 ? thisnode.child2 : thisnode.child3
return curnode
end
|
function findkeyless(t::BalancedTree23, k)
curnode = t.rootloc
for depthcount = 1 : t.depth - 1
@inbounds thisnode = t.tree[curnode]
cmp = thisnode.child3 == 0 ?
cmp2le_nonleaf(t.ord, thisnode, k) :
cmp3le_nonleaf(t.ord, thisnode, k)
curnode = cmp == 1 ? thisnode.child1 :
cmp == 2 ? thisnode.child2 : thisnode.child3
end
@inbounds thisnode = t.tree[curnode]
cmp = thisnode.child3 == 0 ?
cmp2le_leaf(t.ord, thisnode, k) :
cmp3le_leaf(t.ord, thisnode, k)
curnode = cmp == 1 ? thisnode.child1 :
cmp == 2 ? thisnode.child2 : thisnode.child3
return curnode
end
|
findkeyless
| 292
| 309
|
src/balanced_tree.jl
|
#FILE: DataStructures.jl/test/test_sorted_containers.jl
##CHUNK 1
mk2 = minkeys[cp]
cp += 1
if t.tree[c2].parent != anc
throw(ErrorException("Parent/child2 links do not match"))
end
c3 = t.tree[anc].child3
my_assert(s == levstart[curdepth] ||
lt(t.ord,mk1,mk2) || (!lt(t.ord,mk2,mk1) && allowdups))
if c3 > 0
if t.tree[c3].parent != anc
throw(ErrorException("Parent/child3 links do not match"))
end
mk3 = minkeys[cp]
cp += 1
my_assert(lt(t.ord,mk2, mk3) ||
!lt(t.ord,mk3,mk2) && allowdups)
end
if s > levstart[curdepth]
minkeys[s] = mk1
end
##CHUNK 2
my_assert(c1 == bfstreenodes[cp])
if s > levstart[curdepth]
mk1 = minkeys[cp]
end
cp += 1
if t.tree[c1].parent != anc
throw(ErrorException("Parent/child1 links do not match"))
end
c2 = t.tree[anc].child2
my_assert(c2 == bfstreenodes[cp])
mk2 = minkeys[cp]
cp += 1
if t.tree[c2].parent != anc
throw(ErrorException("Parent/child2 links do not match"))
end
c3 = t.tree[anc].child3
my_assert(s == levstart[curdepth] ||
lt(t.ord,mk1,mk2) || (!lt(t.ord,mk2,mk1) && allowdups))
if c3 > 0
if t.tree[c3].parent != anc
#CURRENT FILE: DataStructures.jl/src/balanced_tree.jl
##CHUNK 1
@inbounds thisnode = t.tree[curnode]
cmp = thisnode.child3 == 0 ?
cmp2_nonleaf(t.ord, thisnode, k) :
cmp3_nonleaf(t.ord, thisnode, k)
curnode = cmp == 1 ? thisnode.child1 :
cmp == 2 ? thisnode.child2 : thisnode.child3
end
@inbounds thisnode = t.tree[curnode]
cmp = thisnode.child3 == 0 ?
cmp2_leaf(t.ord, thisnode, k) :
cmp3_leaf(t.ord, thisnode, k)
curnode = cmp == 1 ? thisnode.child1 :
cmp == 2 ? thisnode.child2 : thisnode.child3
@inbounds return curnode, (curnode > 2 && eq(t.ord, t.data[curnode].k, k))
end
## The findkeyless function finds the index of a (key,data) pair in the tree that
## with the greatest key that is less than the given key. If there is no
## key less than the given key, then it returns 1 (the before-start node).
##CHUNK 2
## where the given key lives (if it is present), or
## if the key is not present, to the lower bound for the key,
## i.e., the data item that comes immediately before it.
## If there are multiple equal keys, then it finds the last one.
## It returns the index of the key found and a boolean indicating
## whether the exact key was found or not.
function findkey(t::BalancedTree23, k)
curnode = t.rootloc
for depthcount = 1 : t.depth - 1
@inbounds thisnode = t.tree[curnode]
cmp = thisnode.child3 == 0 ?
cmp2_nonleaf(t.ord, thisnode, k) :
cmp3_nonleaf(t.ord, thisnode, k)
curnode = cmp == 1 ? thisnode.child1 :
cmp == 2 ? thisnode.child2 : thisnode.child3
end
@inbounds thisnode = t.tree[curnode]
cmp = thisnode.child3 == 0 ?
cmp2_leaf(t.ord, thisnode, k) :
##CHUNK 3
treenode::TreeNode,
k)
!lt(o,treenode.splitkey1, k) ? 1 :
!lt(o,treenode.splitkey2, k) ? 2 : 3
end
@inline function cmp3le_leaf(o::Ordering,
treenode::TreeNode,
k)
!lt(o,treenode.splitkey1,k) ? 1 :
(treenode.child3 == 2 || !lt(o,treenode.splitkey2, k)) ? 2 : 3
end
## The empty! function deletes all data in the balanced tree.
## Therefore, it invalidates all indices.
function Base.empty!(t::BalancedTree23)
resize!(t.data,2)
initializeData!(t.data)
##CHUNK 4
## Function cmp3le checks a tree node with three children
## against a given key, and returns 1 if the given key is
## less than or equal to the node's splitkey1, 2 if less than or equal
## to splitkey2, or
## 3 else. Special case
## if the node is a leaf and its right child is the end
## of the sorted order.
@inline function cmp3le_nonleaf(o::Ordering,
treenode::TreeNode,
k)
!lt(o,treenode.splitkey1, k) ? 1 :
!lt(o,treenode.splitkey2, k) ? 2 : 3
end
@inline function cmp3le_leaf(o::Ordering,
treenode::TreeNode,
k)
!lt(o,treenode.splitkey1,k) ? 1 :
##CHUNK 5
## less than the node's splitkey1, 2 if the key is greater than or
## equal to splitkey1 but less than splitkey2, or 3 else. Special case
## if the node is a leaf and its right child is the end
## of the sorted order.
@inline function cmp3_nonleaf(o::Ordering,
treenode::TreeNode,
k)
lt(o, k, treenode.splitkey1) ? 1 :
lt(o, k, treenode.splitkey2) ? 2 : 3
end
@inline function cmp3_leaf(o::Ordering,
treenode::TreeNode,
k)
lt(o, k, treenode.splitkey1) ? 1 :
(treenode.child3 == 2 || lt(o, k, treenode.splitkey2)) ? 2 : 3
end
##CHUNK 6
end
@inline function cmp3_leaf(o::Ordering,
treenode::TreeNode,
k)
lt(o, k, treenode.splitkey1) ? 1 :
(treenode.child3 == 2 || lt(o, k, treenode.splitkey2)) ? 2 : 3
end
## Function cmp2le checks a tree node with two children
## against a given key, and returns 1 if the given key is
## less than or equal to the node's splitkey or 2 else. Special case
## if the node is a leaf and its right child is the end
## of the sorted order.
@inline function cmp2le_nonleaf(o::Ordering,
treenode::TreeNode,
k)
##CHUNK 7
!lt(o,treenode.splitkey1,k) ? 1 : 2
end
@inline function cmp2le_leaf(o::Ordering,
treenode::TreeNode,
k)
treenode.child2 == 2 || !lt(o,treenode.splitkey1,k) ? 1 : 2
end
## Function cmp3le checks a tree node with three children
## against a given key, and returns 1 if the given key is
## less than or equal to the node's splitkey1, 2 if less than or equal
## to splitkey2, or
## 3 else. Special case
## if the node is a leaf and its right child is the end
## of the sorted order.
@inline function cmp3le_nonleaf(o::Ordering,
##CHUNK 8
## if the node is a leaf and its right child is the end
## of the sorted order.
@inline function cmp2_nonleaf(o::Ordering,
treenode::TreeNode,
k)
lt(o, k, treenode.splitkey1) ? 1 : 2
end
@inline function cmp2_leaf(o::Ordering,
treenode::TreeNode,
k)
(treenode.child2 == 2) ||
lt(o, k, treenode.splitkey1) ? 1 : 2
end
## Function cmp3 checks a tree node with three children
## against a given key, and returns 1 if the given key is
|
358
| 520
|
DataStructures.jl
| 10
|
function Base.insert!(t::BalancedTree23{K,D,Ord}, k, d, allowdups::Bool) where {K,D,Ord <: Ordering}
## First we find the greatest data node that is <= k.
leafind, exactfound = findkey(t, k)
parent = t.data[leafind].parent
## The following code is necessary because in the case of a
## brand new tree, the initial tree and data entries were incompletely
## initialized by the constructor. In this case, the call to insert!
## underway carries
## valid K and D values, so these valid values may now be
## stored in the dummy placeholder nodes so that they no
## longer hold undefined references.
if size(t.data,1) == 2
@invariant t.rootloc == 1 && t.depth == 1
t.tree[1] = TreeNode{K}(t.tree[1].child1, t.tree[1].child2,
t.tree[1].child3, t.tree[1].parent,
k, k)
t.data[1] = KDRec{K,D}(t.data[1].parent, k, d)
t.data[2] = KDRec{K,D}(t.data[2].parent, k, d)
end
## If we have found exactly k in the tree, then we
## replace the data associated with k and return.
if exactfound && !allowdups
t.data[leafind] = KDRec{K,D}(parent, k,d)
return false, leafind
end
# We get here if k was not already found in the tree or
# if duplicates are allowed.
# In this case we insert a new node.
depth = t.depth
ord = t.ord
## Store the new data item in the tree's data array. Later
## go back and fix the parent.
newind = push_or_reuse!(t.data, t.freedatainds, KDRec{K,D}(0,k,d))
push!(t.useddatacells, newind)
p1 = parent
newchild = newind
minkeynewchild = k
splitroot = false
curdepth = depth
existingchild = leafind
## This loop ascends the tree (i.e., follows the path from a leaf to the root)
## starting from the parent p1 of
## where the new key k will go.
## Variables updated by the loop:
## p1: parent of where the new node goes
## newchild: index of the child to be inserted
## minkeynewchild: the minimum key in the subtree rooted at newchild
## existingchild: a child of p1; the newchild must
## be inserted in the slot to the right of existingchild
## curdepth: depth of newchild
## For each 3-node we encounter
## during the ascent, we add a new child, which requires splitting
## the 3-node into two 2-nodes. Then we keep going until we hit the root.
## If we encounter a 2-node, then the ascent can stop; we can
## change the 2-node to a 3-node with the new child.
while true
# Let newchild1,...newchild4 be the new children of
# the parent node
# Initially, take the three children of the existing parent
# node and set newchild4 to 0.
newchild1 = t.tree[p1].child1
newchild2 = t.tree[p1].child2
minkeychild2 = t.tree[p1].splitkey1
newchild3 = t.tree[p1].child3
minkeychild3 = t.tree[p1].splitkey2
p1parent = t.tree[p1].parent
newchild4 = 0
# Now figure out which of the 4 children is the new node
# and insert it into newchild1 ... newchild4
if newchild1 == existingchild
newchild4 = newchild3
minkeychild4 = minkeychild3
newchild3 = newchild2
minkeychild3 = minkeychild2
newchild2 = newchild
minkeychild2 = minkeynewchild
elseif newchild2 == existingchild
newchild4 = newchild3
minkeychild4 = minkeychild3
newchild3 = newchild
minkeychild3 = minkeynewchild
elseif newchild3 == existingchild
newchild4 = newchild
minkeychild4 = minkeynewchild
else
throw(AssertionError("Tree structure is corrupted 1"))
end
# Two cases: either we need to split the tree node
# if newchild4>0 else we convert a 2-node to a 3-node
# if newchild4==0
if newchild4 == 0
# Change the parent from a 2-node to a 3-node
t.tree[p1] = TreeNode{K}(newchild1, newchild2, newchild3,
p1parent, minkeychild2, minkeychild3)
if curdepth == depth
replaceparent!(t.data, newchild, p1)
else
replaceparent!(t.tree, newchild, p1)
end
break
end
# Split the parent
t.tree[p1] = TreeNode{K}(newchild1, newchild2, 0,
p1parent, minkeychild2, minkeychild2)
newtreenode = TreeNode{K}(newchild3, newchild4, 0,
p1parent, minkeychild4, minkeychild2)
newparentnum = push_or_reuse!(t.tree, t.freetreeinds, newtreenode)
if curdepth == depth
replaceparent!(t.data, newchild2, p1)
replaceparent!(t.data, newchild3, newparentnum)
replaceparent!(t.data, newchild4, newparentnum)
else
replaceparent!(t.tree, newchild2, p1)
replaceparent!(t.tree, newchild3, newparentnum)
replaceparent!(t.tree, newchild4, newparentnum)
end
# Update the loop variables for the next level of the
# ascension
existingchild = p1
newchild = newparentnum
p1 = p1parent
minkeynewchild = minkeychild3
curdepth -= 1
if curdepth == 0
splitroot = true
break
end
end
# If the root has been split, then we need to add a level
# to the tree that is the parent of the old root and the new node.
if splitroot
@invariant existingchild == t.rootloc
newroot = TreeNode{K}(existingchild, newchild, 0,
0, minkeynewchild, minkeynewchild)
newrootloc = push_or_reuse!(t.tree, t.freetreeinds, newroot)
replaceparent!(t.tree, existingchild, newrootloc)
replaceparent!(t.tree, newchild, newrootloc)
t.rootloc = newrootloc
t.depth += 1
end
return true, newind
end
|
function Base.insert!(t::BalancedTree23{K,D,Ord}, k, d, allowdups::Bool) where {K,D,Ord <: Ordering}
## First we find the greatest data node that is <= k.
leafind, exactfound = findkey(t, k)
parent = t.data[leafind].parent
## The following code is necessary because in the case of a
## brand new tree, the initial tree and data entries were incompletely
## initialized by the constructor. In this case, the call to insert!
## underway carries
## valid K and D values, so these valid values may now be
## stored in the dummy placeholder nodes so that they no
## longer hold undefined references.
if size(t.data,1) == 2
@invariant t.rootloc == 1 && t.depth == 1
t.tree[1] = TreeNode{K}(t.tree[1].child1, t.tree[1].child2,
t.tree[1].child3, t.tree[1].parent,
k, k)
t.data[1] = KDRec{K,D}(t.data[1].parent, k, d)
t.data[2] = KDRec{K,D}(t.data[2].parent, k, d)
end
## If we have found exactly k in the tree, then we
## replace the data associated with k and return.
if exactfound && !allowdups
t.data[leafind] = KDRec{K,D}(parent, k,d)
return false, leafind
end
# We get here if k was not already found in the tree or
# if duplicates are allowed.
# In this case we insert a new node.
depth = t.depth
ord = t.ord
## Store the new data item in the tree's data array. Later
## go back and fix the parent.
newind = push_or_reuse!(t.data, t.freedatainds, KDRec{K,D}(0,k,d))
push!(t.useddatacells, newind)
p1 = parent
newchild = newind
minkeynewchild = k
splitroot = false
curdepth = depth
existingchild = leafind
## This loop ascends the tree (i.e., follows the path from a leaf to the root)
## starting from the parent p1 of
## where the new key k will go.
## Variables updated by the loop:
## p1: parent of where the new node goes
## newchild: index of the child to be inserted
## minkeynewchild: the minimum key in the subtree rooted at newchild
## existingchild: a child of p1; the newchild must
## be inserted in the slot to the right of existingchild
## curdepth: depth of newchild
## For each 3-node we encounter
## during the ascent, we add a new child, which requires splitting
## the 3-node into two 2-nodes. Then we keep going until we hit the root.
## If we encounter a 2-node, then the ascent can stop; we can
## change the 2-node to a 3-node with the new child.
while true
# Let newchild1,...newchild4 be the new children of
# the parent node
# Initially, take the three children of the existing parent
# node and set newchild4 to 0.
newchild1 = t.tree[p1].child1
newchild2 = t.tree[p1].child2
minkeychild2 = t.tree[p1].splitkey1
newchild3 = t.tree[p1].child3
minkeychild3 = t.tree[p1].splitkey2
p1parent = t.tree[p1].parent
newchild4 = 0
# Now figure out which of the 4 children is the new node
# and insert it into newchild1 ... newchild4
if newchild1 == existingchild
newchild4 = newchild3
minkeychild4 = minkeychild3
newchild3 = newchild2
minkeychild3 = minkeychild2
newchild2 = newchild
minkeychild2 = minkeynewchild
elseif newchild2 == existingchild
newchild4 = newchild3
minkeychild4 = minkeychild3
newchild3 = newchild
minkeychild3 = minkeynewchild
elseif newchild3 == existingchild
newchild4 = newchild
minkeychild4 = minkeynewchild
else
throw(AssertionError("Tree structure is corrupted 1"))
end
# Two cases: either we need to split the tree node
# if newchild4>0 else we convert a 2-node to a 3-node
# if newchild4==0
if newchild4 == 0
# Change the parent from a 2-node to a 3-node
t.tree[p1] = TreeNode{K}(newchild1, newchild2, newchild3,
p1parent, minkeychild2, minkeychild3)
if curdepth == depth
replaceparent!(t.data, newchild, p1)
else
replaceparent!(t.tree, newchild, p1)
end
break
end
# Split the parent
t.tree[p1] = TreeNode{K}(newchild1, newchild2, 0,
p1parent, minkeychild2, minkeychild2)
newtreenode = TreeNode{K}(newchild3, newchild4, 0,
p1parent, minkeychild4, minkeychild2)
newparentnum = push_or_reuse!(t.tree, t.freetreeinds, newtreenode)
if curdepth == depth
replaceparent!(t.data, newchild2, p1)
replaceparent!(t.data, newchild3, newparentnum)
replaceparent!(t.data, newchild4, newparentnum)
else
replaceparent!(t.tree, newchild2, p1)
replaceparent!(t.tree, newchild3, newparentnum)
replaceparent!(t.tree, newchild4, newparentnum)
end
# Update the loop variables for the next level of the
# ascension
existingchild = p1
newchild = newparentnum
p1 = p1parent
minkeynewchild = minkeychild3
curdepth -= 1
if curdepth == 0
splitroot = true
break
end
end
# If the root has been split, then we need to add a level
# to the tree that is the parent of the old root and the new node.
if splitroot
@invariant existingchild == t.rootloc
newroot = TreeNode{K}(existingchild, newchild, 0,
0, minkeynewchild, minkeynewchild)
newrootloc = push_or_reuse!(t.tree, t.freetreeinds, newroot)
replaceparent!(t.tree, existingchild, newrootloc)
replaceparent!(t.tree, newchild, newrootloc)
t.rootloc = newrootloc
t.depth += 1
end
return true, newind
end
|
[
358,
520
] |
function Base.insert!(t::BalancedTree23{K,D,Ord}, k, d, allowdups::Bool) where {K,D,Ord <: Ordering}
## First we find the greatest data node that is <= k.
leafind, exactfound = findkey(t, k)
parent = t.data[leafind].parent
## The following code is necessary because in the case of a
## brand new tree, the initial tree and data entries were incompletely
## initialized by the constructor. In this case, the call to insert!
## underway carries
## valid K and D values, so these valid values may now be
## stored in the dummy placeholder nodes so that they no
## longer hold undefined references.
if size(t.data,1) == 2
@invariant t.rootloc == 1 && t.depth == 1
t.tree[1] = TreeNode{K}(t.tree[1].child1, t.tree[1].child2,
t.tree[1].child3, t.tree[1].parent,
k, k)
t.data[1] = KDRec{K,D}(t.data[1].parent, k, d)
t.data[2] = KDRec{K,D}(t.data[2].parent, k, d)
end
## If we have found exactly k in the tree, then we
## replace the data associated with k and return.
if exactfound && !allowdups
t.data[leafind] = KDRec{K,D}(parent, k,d)
return false, leafind
end
# We get here if k was not already found in the tree or
# if duplicates are allowed.
# In this case we insert a new node.
depth = t.depth
ord = t.ord
## Store the new data item in the tree's data array. Later
## go back and fix the parent.
newind = push_or_reuse!(t.data, t.freedatainds, KDRec{K,D}(0,k,d))
push!(t.useddatacells, newind)
p1 = parent
newchild = newind
minkeynewchild = k
splitroot = false
curdepth = depth
existingchild = leafind
## This loop ascends the tree (i.e., follows the path from a leaf to the root)
## starting from the parent p1 of
## where the new key k will go.
## Variables updated by the loop:
## p1: parent of where the new node goes
## newchild: index of the child to be inserted
## minkeynewchild: the minimum key in the subtree rooted at newchild
## existingchild: a child of p1; the newchild must
## be inserted in the slot to the right of existingchild
## curdepth: depth of newchild
## For each 3-node we encounter
## during the ascent, we add a new child, which requires splitting
## the 3-node into two 2-nodes. Then we keep going until we hit the root.
## If we encounter a 2-node, then the ascent can stop; we can
## change the 2-node to a 3-node with the new child.
while true
# Let newchild1,...newchild4 be the new children of
# the parent node
# Initially, take the three children of the existing parent
# node and set newchild4 to 0.
newchild1 = t.tree[p1].child1
newchild2 = t.tree[p1].child2
minkeychild2 = t.tree[p1].splitkey1
newchild3 = t.tree[p1].child3
minkeychild3 = t.tree[p1].splitkey2
p1parent = t.tree[p1].parent
newchild4 = 0
# Now figure out which of the 4 children is the new node
# and insert it into newchild1 ... newchild4
if newchild1 == existingchild
newchild4 = newchild3
minkeychild4 = minkeychild3
newchild3 = newchild2
minkeychild3 = minkeychild2
newchild2 = newchild
minkeychild2 = minkeynewchild
elseif newchild2 == existingchild
newchild4 = newchild3
minkeychild4 = minkeychild3
newchild3 = newchild
minkeychild3 = minkeynewchild
elseif newchild3 == existingchild
newchild4 = newchild
minkeychild4 = minkeynewchild
else
throw(AssertionError("Tree structure is corrupted 1"))
end
# Two cases: either we need to split the tree node
# if newchild4>0 else we convert a 2-node to a 3-node
# if newchild4==0
if newchild4 == 0
# Change the parent from a 2-node to a 3-node
t.tree[p1] = TreeNode{K}(newchild1, newchild2, newchild3,
p1parent, minkeychild2, minkeychild3)
if curdepth == depth
replaceparent!(t.data, newchild, p1)
else
replaceparent!(t.tree, newchild, p1)
end
break
end
# Split the parent
t.tree[p1] = TreeNode{K}(newchild1, newchild2, 0,
p1parent, minkeychild2, minkeychild2)
newtreenode = TreeNode{K}(newchild3, newchild4, 0,
p1parent, minkeychild4, minkeychild2)
newparentnum = push_or_reuse!(t.tree, t.freetreeinds, newtreenode)
if curdepth == depth
replaceparent!(t.data, newchild2, p1)
replaceparent!(t.data, newchild3, newparentnum)
replaceparent!(t.data, newchild4, newparentnum)
else
replaceparent!(t.tree, newchild2, p1)
replaceparent!(t.tree, newchild3, newparentnum)
replaceparent!(t.tree, newchild4, newparentnum)
end
# Update the loop variables for the next level of the
# ascension
existingchild = p1
newchild = newparentnum
p1 = p1parent
minkeynewchild = minkeychild3
curdepth -= 1
if curdepth == 0
splitroot = true
break
end
end
# If the root has been split, then we need to add a level
# to the tree that is the parent of the old root and the new node.
if splitroot
@invariant existingchild == t.rootloc
newroot = TreeNode{K}(existingchild, newchild, 0,
0, minkeynewchild, minkeynewchild)
newrootloc = push_or_reuse!(t.tree, t.freetreeinds, newroot)
replaceparent!(t.tree, existingchild, newrootloc)
replaceparent!(t.tree, newchild, newrootloc)
t.rootloc = newrootloc
t.depth += 1
end
return true, newind
end
|
function Base.insert!(t::BalancedTree23{K,D,Ord}, k, d, allowdups::Bool) where {K,D,Ord <: Ordering}
## First we find the greatest data node that is <= k.
leafind, exactfound = findkey(t, k)
parent = t.data[leafind].parent
## The following code is necessary because in the case of a
## brand new tree, the initial tree and data entries were incompletely
## initialized by the constructor. In this case, the call to insert!
## underway carries
## valid K and D values, so these valid values may now be
## stored in the dummy placeholder nodes so that they no
## longer hold undefined references.
if size(t.data,1) == 2
@invariant t.rootloc == 1 && t.depth == 1
t.tree[1] = TreeNode{K}(t.tree[1].child1, t.tree[1].child2,
t.tree[1].child3, t.tree[1].parent,
k, k)
t.data[1] = KDRec{K,D}(t.data[1].parent, k, d)
t.data[2] = KDRec{K,D}(t.data[2].parent, k, d)
end
## If we have found exactly k in the tree, then we
## replace the data associated with k and return.
if exactfound && !allowdups
t.data[leafind] = KDRec{K,D}(parent, k,d)
return false, leafind
end
# We get here if k was not already found in the tree or
# if duplicates are allowed.
# In this case we insert a new node.
depth = t.depth
ord = t.ord
## Store the new data item in the tree's data array. Later
## go back and fix the parent.
newind = push_or_reuse!(t.data, t.freedatainds, KDRec{K,D}(0,k,d))
push!(t.useddatacells, newind)
p1 = parent
newchild = newind
minkeynewchild = k
splitroot = false
curdepth = depth
existingchild = leafind
## This loop ascends the tree (i.e., follows the path from a leaf to the root)
## starting from the parent p1 of
## where the new key k will go.
## Variables updated by the loop:
## p1: parent of where the new node goes
## newchild: index of the child to be inserted
## minkeynewchild: the minimum key in the subtree rooted at newchild
## existingchild: a child of p1; the newchild must
## be inserted in the slot to the right of existingchild
## curdepth: depth of newchild
## For each 3-node we encounter
## during the ascent, we add a new child, which requires splitting
## the 3-node into two 2-nodes. Then we keep going until we hit the root.
## If we encounter a 2-node, then the ascent can stop; we can
## change the 2-node to a 3-node with the new child.
while true
# Let newchild1,...newchild4 be the new children of
# the parent node
# Initially, take the three children of the existing parent
# node and set newchild4 to 0.
newchild1 = t.tree[p1].child1
newchild2 = t.tree[p1].child2
minkeychild2 = t.tree[p1].splitkey1
newchild3 = t.tree[p1].child3
minkeychild3 = t.tree[p1].splitkey2
p1parent = t.tree[p1].parent
newchild4 = 0
# Now figure out which of the 4 children is the new node
# and insert it into newchild1 ... newchild4
if newchild1 == existingchild
newchild4 = newchild3
minkeychild4 = minkeychild3
newchild3 = newchild2
minkeychild3 = minkeychild2
newchild2 = newchild
minkeychild2 = minkeynewchild
elseif newchild2 == existingchild
newchild4 = newchild3
minkeychild4 = minkeychild3
newchild3 = newchild
minkeychild3 = minkeynewchild
elseif newchild3 == existingchild
newchild4 = newchild
minkeychild4 = minkeynewchild
else
throw(AssertionError("Tree structure is corrupted 1"))
end
# Two cases: either we need to split the tree node
# if newchild4>0 else we convert a 2-node to a 3-node
# if newchild4==0
if newchild4 == 0
# Change the parent from a 2-node to a 3-node
t.tree[p1] = TreeNode{K}(newchild1, newchild2, newchild3,
p1parent, minkeychild2, minkeychild3)
if curdepth == depth
replaceparent!(t.data, newchild, p1)
else
replaceparent!(t.tree, newchild, p1)
end
break
end
# Split the parent
t.tree[p1] = TreeNode{K}(newchild1, newchild2, 0,
p1parent, minkeychild2, minkeychild2)
newtreenode = TreeNode{K}(newchild3, newchild4, 0,
p1parent, minkeychild4, minkeychild2)
newparentnum = push_or_reuse!(t.tree, t.freetreeinds, newtreenode)
if curdepth == depth
replaceparent!(t.data, newchild2, p1)
replaceparent!(t.data, newchild3, newparentnum)
replaceparent!(t.data, newchild4, newparentnum)
else
replaceparent!(t.tree, newchild2, p1)
replaceparent!(t.tree, newchild3, newparentnum)
replaceparent!(t.tree, newchild4, newparentnum)
end
# Update the loop variables for the next level of the
# ascension
existingchild = p1
newchild = newparentnum
p1 = p1parent
minkeynewchild = minkeychild3
curdepth -= 1
if curdepth == 0
splitroot = true
break
end
end
# If the root has been split, then we need to add a level
# to the tree that is the parent of the old root and the new node.
if splitroot
@invariant existingchild == t.rootloc
newroot = TreeNode{K}(existingchild, newchild, 0,
0, minkeynewchild, minkeynewchild)
newrootloc = push_or_reuse!(t.tree, t.freetreeinds, newroot)
replaceparent!(t.tree, existingchild, newrootloc)
replaceparent!(t.tree, newchild, newrootloc)
t.rootloc = newrootloc
t.depth += 1
end
return true, newind
end
|
size
| 358
| 520
|
src/balanced_tree.jl
|
#FILE: DataStructures.jl/src/red_black_tree.jl
##CHUNK 1
function Base.insert!(tree::RBTree{K}, d::K) where K
# if the key exists in the tree, no need to insert
haskey(tree, d) && return tree
# insert, if not present in the tree
node = RBTreeNode{K}(d)
node.leftChild = node.rightChild = tree.nil
insert_node!(tree, node)
if node.parent == nothing
node.color = false
elseif node.parent.parent == nothing
;
else
fix_insert!(tree, node)
end
tree.count += 1
return tree
end
##CHUNK 2
end
end
tree.root.color = false
end
"""
insert!(tree, key)
Inserts `key` in the `tree` if it is not present.
"""
function Base.insert!(tree::RBTree{K}, d::K) where K
# if the key exists in the tree, no need to insert
haskey(tree, d) && return tree
# insert, if not present in the tree
node = RBTreeNode{K}(d)
node.leftChild = node.rightChild = tree.nil
insert_node!(tree, node)
#CURRENT FILE: DataStructures.jl/src/balanced_tree.jl
##CHUNK 1
end
@inbounds thisnode = t.tree[curnode]
cmp = thisnode.child3 == 0 ?
cmp2le_leaf(t.ord, thisnode, k) :
cmp3le_leaf(t.ord, thisnode, k)
curnode = cmp == 1 ? thisnode.child1 :
cmp == 2 ? thisnode.child2 : thisnode.child3
return curnode
end
## The following are helper routines for the insert! and delete! functions.
## They replace the 'parent' field of either an internal tree node or
## a data node at the bottom tree level.
function replaceparent!(data::Vector{KDRec{K,D}}, whichind::Int, newparent::Int) where {K,D}
data[whichind] = KDRec{K,D}(newparent, data[whichind].k, data[whichind].d)
return nothing
end
##CHUNK 2
if c3 != it && c3 > 0
newchildcount += 1
t.deletionchild[newchildcount] = c3
t.deletionleftkey[newchildcount] = t.data[c3].k
end
@invariant newchildcount == 1 || newchildcount == 2
push!(t.freedatainds, it)
pop!(t.useddatacells,it)
defaultKey = t.tree[1].splitkey1
curdepth = t.depth
mustdeleteroot = false
pparent = -1
## The following loop ascends the tree and contracts nodes (reduces their
## number of children) as
## needed. If newchildcount == 2 or 3, then the ascent is terminated
## and a node is created with 2 or 3 children.
## If newchildcount == 1, then the ascent must continue since a tree
## node cannot have one child.
##CHUNK 3
end
# Build a balanced tree from an iterable in which the data is already
# sorted
function BalancedTree23{K,D,Ord}(::Val{true},
iterable,
ord::Ord,
allowdups::Bool) where {K, D, Ord <: Ordering}
m = BalancedTree23{K,D,Ord}(ord)
lengthdata = length(m.data)
@assert lengthdata == 2
firsttrip = true
for (k,d) in iterable
# Must initialize the before-start and past-end markers
# with live data to prevent references to undefined fields
# later
if firsttrip
m.data[1] = KDRec{K,D}(m.data[1].parent, k, d)
m.data[2] = KDRec{K,D}(m.data[2].parent, k, d)
##CHUNK 4
lengthdata = length(m.data)
@assert lengthdata == 2
firsttrip = true
for (k,d) in iterable
# Must initialize the before-start and past-end markers
# with live data to prevent references to undefined fields
# later
if firsttrip
m.data[1] = KDRec{K,D}(m.data[1].parent, k, d)
m.data[2] = KDRec{K,D}(m.data[2].parent, k, d)
end
if !firsttrip
lt(ord, k, m.data[lengthdata].k) && throw(ArgumentError("Keys out of order"))
if !allowdups
!lt(ord, m.data[lengthdata].k, k) && throw(ArgumentError("Repeated key"))
end
end
push!(m.data, KDRec{K,D}(0, convert(K,k), convert(D,d)))
##CHUNK 5
mutable struct BalancedTree23{K, D, Ord <: Ordering}
ord::Ord
data::Vector{KDRec{K,D}}
tree::Vector{TreeNode{K}}
rootloc::Int
depth::Int
freetreeinds::Vector{Int}
freedatainds::Vector{Int}
useddatacells::BitSet
# The next two arrays are used as a workspace by the delete!
# function.
deletionchild::Vector{Int}
deletionleftkey::Vector{K}
function BalancedTree23{K,D,Ord}(ord1::Ord) where {K,D,Ord<:Ordering}
tree1 = Vector{TreeNode{K}}(undef, 1)
initializeTree!(tree1)
data1 = Vector{KDRec{K,D}}(undef, 2)
initializeData!(data1)
u1 = BitSet()
push!(u1, 1, 2)
##CHUNK 6
function Base.delete!(t::BalancedTree23{K,D,Ord}, it::Int) where {K,D,Ord<:Ordering}
## Put the cell indexed by 'it' into the deletion list.
##
## Create the following data items maintained in the
## upcoming loop.
##
## p is a tree-node ancestor of the deleted node
## The children of p are stored in
## t.deletionchild[..]
## The number of these children is newchildcount, which is 1, 2 or 3.
## The keys that lower bound the children
## are stored in t.deletionleftkey[..]
## There is a special case for t.deletionleftkey[1]; the
## flag deletionleftkey1_valid indicates that the left key
## for the immediate right neighbor of the
## deleted node has not yet been been stored in the tree.
## Once it is stored, t.deletionleftkey[1] is no longer needed
## or used.
##CHUNK 7
# function.
deletionchild::Vector{Int}
deletionleftkey::Vector{K}
function BalancedTree23{K,D,Ord}(ord1::Ord) where {K,D,Ord<:Ordering}
tree1 = Vector{TreeNode{K}}(undef, 1)
initializeTree!(tree1)
data1 = Vector{KDRec{K,D}}(undef, 2)
initializeData!(data1)
u1 = BitSet()
push!(u1, 1, 2)
new{K,D,Ord}(ord1, data1, tree1, 1, 1, Vector{Int}(), Vector{Int}(),
u1,
Vector{Int}(undef, 3), Vector{K}(undef, 3))
end
end
## Function cmp2 checks a tree node with two children
## against a given key, and returns 1 if the given key is
## less than the node's splitkey or 2 else. Special case
##CHUNK 8
## The first and second entries of the data array are dummy placeholders
## for the beginning and end of the sorted order of the keys
## tree: the nodes of a 2-3 tree that sits above the data.
## rootloc: the index of the entry of tree (i.e., a subscript to
## treenodes) that is the tree's root
## depth: the depth of the tree, (number
## of tree levels, not counting the level of data at the bottom)
## depth==1 means that there is a single root node
## whose children are data nodes.
## freetreeinds: Array of indices of free locations in the
## tree array (locations are freed due to deletion)
## freedatainds: Array of indices of free locations in the
## data array (locations are freed due to deletion)
## useddatacells: BitSet (i.e., bit vector) showing which
## data cells are taken. The complementary positions are
## exactly those stored in freedatainds. This array is
## used only for error checking.
## deletionchild and deletionleftkey are two work-arrays
## for the delete function.
|
655
| 984
|
DataStructures.jl
| 11
|
function Base.delete!(t::BalancedTree23{K,D,Ord}, it::Int) where {K,D,Ord<:Ordering}
## Put the cell indexed by 'it' into the deletion list.
##
## Create the following data items maintained in the
## upcoming loop.
##
## p is a tree-node ancestor of the deleted node
## The children of p are stored in
## t.deletionchild[..]
## The number of these children is newchildcount, which is 1, 2 or 3.
## The keys that lower bound the children
## are stored in t.deletionleftkey[..]
## There is a special case for t.deletionleftkey[1]; the
## flag deletionleftkey1_valid indicates that the left key
## for the immediate right neighbor of the
## deleted node has not yet been been stored in the tree.
## Once it is stored, t.deletionleftkey[1] is no longer needed
## or used.
## The flag mustdeleteroot means that the tree has contracted
## enough that it loses a level.
p = t.data[it].parent
newchildcount = 0
c1 = t.tree[p].child1
deletionleftkey1_valid = true
if c1 != it
deletionleftkey1_valid = false
newchildcount += 1
t.deletionchild[newchildcount] = c1
t.deletionleftkey[newchildcount] = t.data[c1].k
end
c2 = t.tree[p].child2
if c2 != it
newchildcount += 1
t.deletionchild[newchildcount] = c2
t.deletionleftkey[newchildcount] = t.data[c2].k
end
c3 = t.tree[p].child3
if c3 != it && c3 > 0
newchildcount += 1
t.deletionchild[newchildcount] = c3
t.deletionleftkey[newchildcount] = t.data[c3].k
end
@invariant newchildcount == 1 || newchildcount == 2
push!(t.freedatainds, it)
pop!(t.useddatacells,it)
defaultKey = t.tree[1].splitkey1
curdepth = t.depth
mustdeleteroot = false
pparent = -1
## The following loop ascends the tree and contracts nodes (reduces their
## number of children) as
## needed. If newchildcount == 2 or 3, then the ascent is terminated
## and a node is created with 2 or 3 children.
## If newchildcount == 1, then the ascent must continue since a tree
## node cannot have one child.
while true
pparent = t.tree[p].parent
## Simple cases when the new child count is 2 or 3
if newchildcount == 2
t.tree[p] = TreeNode{K}(t.deletionchild[1],
t.deletionchild[2], 0, pparent,
t.deletionleftkey[2], defaultKey)
break
end
if newchildcount == 3
t.tree[p] = TreeNode{K}(t.deletionchild[1], t.deletionchild[2],
t.deletionchild[3], pparent,
t.deletionleftkey[2], t.deletionleftkey[3])
break
end
@invariant newchildcount == 1
## For the rest of this loop, we cover the case
## that p has one child.
## If newchildcount == 1 and curdepth==1, this means that
## the root of the tree has only one child. In this case, we can
## delete the root and make its one child the new root (see below).
if curdepth == 1
mustdeleteroot = true
break
end
## We now branch on three cases depending on whether p is child1,
## child2 or child3 of its parent.
if t.tree[pparent].child1 == p
rightsib = t.tree[pparent].child2
## Here p is child1 and rightsib is child2.
## If rightsib has 2 children, then p and
## rightsib are merged into a single node
## that has three children.
## If rightsib has 3 children, then p and
## rightsib are reformed so that each has
## two children.
if t.tree[rightsib].child3 == 0
rc1 = t.tree[rightsib].child1
rc2 = t.tree[rightsib].child2
t.tree[p] = TreeNode{K}(t.deletionchild[1],
rc1, rc2,
pparent,
t.tree[pparent].splitkey1,
t.tree[rightsib].splitkey1)
if curdepth == t.depth
replaceparent!(t.data, rc1, p)
replaceparent!(t.data, rc2, p)
else
replaceparent!(t.tree, rc1, p)
replaceparent!(t.tree, rc2, p)
end
push!(t.freetreeinds, rightsib)
newchildcount = 1
t.deletionchild[1] = p
else
rc1 = t.tree[rightsib].child1
t.tree[p] = TreeNode{K}(t.deletionchild[1], rc1, 0,
pparent,
t.tree[pparent].splitkey1,
defaultKey)
sk1 = t.tree[rightsib].splitkey1
t.tree[rightsib] = TreeNode{K}(t.tree[rightsib].child2,
t.tree[rightsib].child3,
0,
pparent,
t.tree[rightsib].splitkey2,
defaultKey)
if curdepth == t.depth
replaceparent!(t.data, rc1, p)
else
replaceparent!(t.tree, rc1, p)
end
newchildcount = 2
t.deletionchild[1] = p
t.deletionchild[2] = rightsib
t.deletionleftkey[2] = sk1
end
## If pparent had a third child (besides p and rightsib)
## then we add this to t.deletionchild
c3 = t.tree[pparent].child3
if c3 > 0
newchildcount += 1
t.deletionchild[newchildcount] = c3
t.deletionleftkey[newchildcount] = t.tree[pparent].splitkey2
end
p = pparent
elseif t.tree[pparent].child2 == p
## Here p is child2 and leftsib is child1.
## If leftsib has 2 children, then p and
## leftsib are merged into a single node
## that has three children.
## If leftsib has 3 children, then p and
## leftsib are reformed so that each has
## two children.
leftsib = t.tree[pparent].child1
lk = deletionleftkey1_valid ?
t.deletionleftkey[1] :
t.tree[pparent].splitkey1
if t.tree[leftsib].child3 == 0
lc1 = t.tree[leftsib].child1
lc2 = t.tree[leftsib].child2
t.tree[p] = TreeNode{K}(lc1, lc2,
t.deletionchild[1],
pparent,
t.tree[leftsib].splitkey1,
lk)
if curdepth == t.depth
replaceparent!(t.data, lc1, p)
replaceparent!(t.data, lc2, p)
else
replaceparent!(t.tree, lc1, p)
replaceparent!(t.tree, lc2, p)
end
push!(t.freetreeinds, leftsib)
newchildcount = 1
t.deletionchild[1] = p
else
lc3 = t.tree[leftsib].child3
t.tree[p] = TreeNode{K}(lc3, t.deletionchild[1], 0,
pparent, lk, defaultKey)
sk2 = t.tree[leftsib].splitkey2
t.tree[leftsib] = TreeNode{K}(t.tree[leftsib].child1,
t.tree[leftsib].child2,
0, pparent,
t.tree[leftsib].splitkey1,
defaultKey)
if curdepth == t.depth
replaceparent!(t.data, lc3, p)
else
replaceparent!(t.tree, lc3, p)
end
newchildcount = 2
t.deletionchild[1] = leftsib
t.deletionchild[2] = p
t.deletionleftkey[2] = sk2
end
## If pparent had a third child (besides p and leftsib)
## then we add this to t.deletionchild
c3 = t.tree[pparent].child3
if c3 > 0
newchildcount += 1
t.deletionchild[newchildcount] = c3
t.deletionleftkey[newchildcount] = t.tree[pparent].splitkey2
end
p = pparent
deletionleftkey1_valid = false
else
## Here p is child3 and leftsib is child2.
## If leftsib has 2 children, then p and
## leftsib are merged into a single node
## that has three children.
## If leftsib has 3 children, then p and
## leftsib are reformed so that each has
## two children.
@invariant t.tree[pparent].child3 == p
leftsib = t.tree[pparent].child2
lk = deletionleftkey1_valid ?
t.deletionleftkey[1] :
t.tree[pparent].splitkey2
if t.tree[leftsib].child3 == 0
lc1 = t.tree[leftsib].child1
lc2 = t.tree[leftsib].child2
t.tree[p] = TreeNode{K}(lc1, lc2,
t.deletionchild[1],
pparent,
t.tree[leftsib].splitkey1,
lk)
if curdepth == t.depth
replaceparent!(t.data, lc1, p)
replaceparent!(t.data, lc2, p)
else
replaceparent!(t.tree, lc1, p)
replaceparent!(t.tree, lc2, p)
end
push!(t.freetreeinds, leftsib)
newchildcount = 2
t.deletionchild[1] = t.tree[pparent].child1
t.deletionleftkey[2] = t.tree[pparent].splitkey1
t.deletionchild[2] = p
else
lc3 = t.tree[leftsib].child3
t.tree[p] = TreeNode{K}(lc3, t.deletionchild[1], 0,
pparent, lk, defaultKey)
sk2 = t.tree[leftsib].splitkey2
t.tree[leftsib] = TreeNode{K}(t.tree[leftsib].child1,
t.tree[leftsib].child2,
0, pparent,
t.tree[leftsib].splitkey1,
defaultKey)
if curdepth == t.depth
replaceparent!(t.data, lc3, p)
else
replaceparent!(t.tree, lc3, p)
end
newchildcount = 3
t.deletionchild[1] = t.tree[pparent].child1
t.deletionchild[2] = leftsib
t.deletionchild[3] = p
t.deletionleftkey[2] = t.tree[pparent].splitkey1
t.deletionleftkey[3] = sk2
end
p = pparent
deletionleftkey1_valid = false
end
curdepth -= 1
end
if mustdeleteroot
@invariant !deletionleftkey1_valid
@invariant p == t.rootloc
t.rootloc = t.deletionchild[1]
t.depth -= 1
push!(t.freetreeinds, p)
end
## If deletionleftkey1_valid, this means that the new
## min key of the deleted node and its right neighbors
## has never been stored in the tree. It must be stored
## as splitkey1 or splitkey2 of some ancestor of the
## deleted node, so we continue ascending the tree
## until we find a node which has p (and therefore the
## deleted node) as its descendent through its second
## or third child.
## It cannot be the case that the deleted node is
## is a descendent of the root always through
## first children, since this would mean the deleted
## node is the leftmost placeholder, which
## cannot be deleted.
if deletionleftkey1_valid
while true
pparentnode = t.tree[pparent]
if pparentnode.child2 == p
t.tree[pparent] = TreeNode{K}(pparentnode.child1,
pparentnode.child2,
pparentnode.child3,
pparentnode.parent,
t.deletionleftkey[1],
pparentnode.splitkey2)
break
elseif pparentnode.child3 == p
t.tree[pparent] = TreeNode{K}(pparentnode.child1,
pparentnode.child2,
pparentnode.child3,
pparentnode.parent,
pparentnode.splitkey1,
t.deletionleftkey[1])
break
else
p = pparent
pparent = pparentnode.parent
curdepth -= 1
@invariant curdepth > 0
end
end
end
return nothing
end
|
function Base.delete!(t::BalancedTree23{K,D,Ord}, it::Int) where {K,D,Ord<:Ordering}
## Put the cell indexed by 'it' into the deletion list.
##
## Create the following data items maintained in the
## upcoming loop.
##
## p is a tree-node ancestor of the deleted node
## The children of p are stored in
## t.deletionchild[..]
## The number of these children is newchildcount, which is 1, 2 or 3.
## The keys that lower bound the children
## are stored in t.deletionleftkey[..]
## There is a special case for t.deletionleftkey[1]; the
## flag deletionleftkey1_valid indicates that the left key
## for the immediate right neighbor of the
## deleted node has not yet been been stored in the tree.
## Once it is stored, t.deletionleftkey[1] is no longer needed
## or used.
## The flag mustdeleteroot means that the tree has contracted
## enough that it loses a level.
p = t.data[it].parent
newchildcount = 0
c1 = t.tree[p].child1
deletionleftkey1_valid = true
if c1 != it
deletionleftkey1_valid = false
newchildcount += 1
t.deletionchild[newchildcount] = c1
t.deletionleftkey[newchildcount] = t.data[c1].k
end
c2 = t.tree[p].child2
if c2 != it
newchildcount += 1
t.deletionchild[newchildcount] = c2
t.deletionleftkey[newchildcount] = t.data[c2].k
end
c3 = t.tree[p].child3
if c3 != it && c3 > 0
newchildcount += 1
t.deletionchild[newchildcount] = c3
t.deletionleftkey[newchildcount] = t.data[c3].k
end
@invariant newchildcount == 1 || newchildcount == 2
push!(t.freedatainds, it)
pop!(t.useddatacells,it)
defaultKey = t.tree[1].splitkey1
curdepth = t.depth
mustdeleteroot = false
pparent = -1
## The following loop ascends the tree and contracts nodes (reduces their
## number of children) as
## needed. If newchildcount == 2 or 3, then the ascent is terminated
## and a node is created with 2 or 3 children.
## If newchildcount == 1, then the ascent must continue since a tree
## node cannot have one child.
while true
pparent = t.tree[p].parent
## Simple cases when the new child count is 2 or 3
if newchildcount == 2
t.tree[p] = TreeNode{K}(t.deletionchild[1],
t.deletionchild[2], 0, pparent,
t.deletionleftkey[2], defaultKey)
break
end
if newchildcount == 3
t.tree[p] = TreeNode{K}(t.deletionchild[1], t.deletionchild[2],
t.deletionchild[3], pparent,
t.deletionleftkey[2], t.deletionleftkey[3])
break
end
@invariant newchildcount == 1
## For the rest of this loop, we cover the case
## that p has one child.
## If newchildcount == 1 and curdepth==1, this means that
## the root of the tree has only one child. In this case, we can
## delete the root and make its one child the new root (see below).
if curdepth == 1
mustdeleteroot = true
break
end
## We now branch on three cases depending on whether p is child1,
## child2 or child3 of its parent.
if t.tree[pparent].child1 == p
rightsib = t.tree[pparent].child2
## Here p is child1 and rightsib is child2.
## If rightsib has 2 children, then p and
## rightsib are merged into a single node
## that has three children.
## If rightsib has 3 children, then p and
## rightsib are reformed so that each has
## two children.
if t.tree[rightsib].child3 == 0
rc1 = t.tree[rightsib].child1
rc2 = t.tree[rightsib].child2
t.tree[p] = TreeNode{K}(t.deletionchild[1],
rc1, rc2,
pparent,
t.tree[pparent].splitkey1,
t.tree[rightsib].splitkey1)
if curdepth == t.depth
replaceparent!(t.data, rc1, p)
replaceparent!(t.data, rc2, p)
else
replaceparent!(t.tree, rc1, p)
replaceparent!(t.tree, rc2, p)
end
push!(t.freetreeinds, rightsib)
newchildcount = 1
t.deletionchild[1] = p
else
rc1 = t.tree[rightsib].child1
t.tree[p] = TreeNode{K}(t.deletionchild[1], rc1, 0,
pparent,
t.tree[pparent].splitkey1,
defaultKey)
sk1 = t.tree[rightsib].splitkey1
t.tree[rightsib] = TreeNode{K}(t.tree[rightsib].child2,
t.tree[rightsib].child3,
0,
pparent,
t.tree[rightsib].splitkey2,
defaultKey)
if curdepth == t.depth
replaceparent!(t.data, rc1, p)
else
replaceparent!(t.tree, rc1, p)
end
newchildcount = 2
t.deletionchild[1] = p
t.deletionchild[2] = rightsib
t.deletionleftkey[2] = sk1
end
## If pparent had a third child (besides p and rightsib)
## then we add this to t.deletionchild
c3 = t.tree[pparent].child3
if c3 > 0
newchildcount += 1
t.deletionchild[newchildcount] = c3
t.deletionleftkey[newchildcount] = t.tree[pparent].splitkey2
end
p = pparent
elseif t.tree[pparent].child2 == p
## Here p is child2 and leftsib is child1.
## If leftsib has 2 children, then p and
## leftsib are merged into a single node
## that has three children.
## If leftsib has 3 children, then p and
## leftsib are reformed so that each has
## two children.
leftsib = t.tree[pparent].child1
lk = deletionleftkey1_valid ?
t.deletionleftkey[1] :
t.tree[pparent].splitkey1
if t.tree[leftsib].child3 == 0
lc1 = t.tree[leftsib].child1
lc2 = t.tree[leftsib].child2
t.tree[p] = TreeNode{K}(lc1, lc2,
t.deletionchild[1],
pparent,
t.tree[leftsib].splitkey1,
lk)
if curdepth == t.depth
replaceparent!(t.data, lc1, p)
replaceparent!(t.data, lc2, p)
else
replaceparent!(t.tree, lc1, p)
replaceparent!(t.tree, lc2, p)
end
push!(t.freetreeinds, leftsib)
newchildcount = 1
t.deletionchild[1] = p
else
lc3 = t.tree[leftsib].child3
t.tree[p] = TreeNode{K}(lc3, t.deletionchild[1], 0,
pparent, lk, defaultKey)
sk2 = t.tree[leftsib].splitkey2
t.tree[leftsib] = TreeNode{K}(t.tree[leftsib].child1,
t.tree[leftsib].child2,
0, pparent,
t.tree[leftsib].splitkey1,
defaultKey)
if curdepth == t.depth
replaceparent!(t.data, lc3, p)
else
replaceparent!(t.tree, lc3, p)
end
newchildcount = 2
t.deletionchild[1] = leftsib
t.deletionchild[2] = p
t.deletionleftkey[2] = sk2
end
## If pparent had a third child (besides p and leftsib)
## then we add this to t.deletionchild
c3 = t.tree[pparent].child3
if c3 > 0
newchildcount += 1
t.deletionchild[newchildcount] = c3
t.deletionleftkey[newchildcount] = t.tree[pparent].splitkey2
end
p = pparent
deletionleftkey1_valid = false
else
## Here p is child3 and leftsib is child2.
## If leftsib has 2 children, then p and
## leftsib are merged into a single node
## that has three children.
## If leftsib has 3 children, then p and
## leftsib are reformed so that each has
## two children.
@invariant t.tree[pparent].child3 == p
leftsib = t.tree[pparent].child2
lk = deletionleftkey1_valid ?
t.deletionleftkey[1] :
t.tree[pparent].splitkey2
if t.tree[leftsib].child3 == 0
lc1 = t.tree[leftsib].child1
lc2 = t.tree[leftsib].child2
t.tree[p] = TreeNode{K}(lc1, lc2,
t.deletionchild[1],
pparent,
t.tree[leftsib].splitkey1,
lk)
if curdepth == t.depth
replaceparent!(t.data, lc1, p)
replaceparent!(t.data, lc2, p)
else
replaceparent!(t.tree, lc1, p)
replaceparent!(t.tree, lc2, p)
end
push!(t.freetreeinds, leftsib)
newchildcount = 2
t.deletionchild[1] = t.tree[pparent].child1
t.deletionleftkey[2] = t.tree[pparent].splitkey1
t.deletionchild[2] = p
else
lc3 = t.tree[leftsib].child3
t.tree[p] = TreeNode{K}(lc3, t.deletionchild[1], 0,
pparent, lk, defaultKey)
sk2 = t.tree[leftsib].splitkey2
t.tree[leftsib] = TreeNode{K}(t.tree[leftsib].child1,
t.tree[leftsib].child2,
0, pparent,
t.tree[leftsib].splitkey1,
defaultKey)
if curdepth == t.depth
replaceparent!(t.data, lc3, p)
else
replaceparent!(t.tree, lc3, p)
end
newchildcount = 3
t.deletionchild[1] = t.tree[pparent].child1
t.deletionchild[2] = leftsib
t.deletionchild[3] = p
t.deletionleftkey[2] = t.tree[pparent].splitkey1
t.deletionleftkey[3] = sk2
end
p = pparent
deletionleftkey1_valid = false
end
curdepth -= 1
end
if mustdeleteroot
@invariant !deletionleftkey1_valid
@invariant p == t.rootloc
t.rootloc = t.deletionchild[1]
t.depth -= 1
push!(t.freetreeinds, p)
end
## If deletionleftkey1_valid, this means that the new
## min key of the deleted node and its right neighbors
## has never been stored in the tree. It must be stored
## as splitkey1 or splitkey2 of some ancestor of the
## deleted node, so we continue ascending the tree
## until we find a node which has p (and therefore the
## deleted node) as its descendent through its second
## or third child.
## It cannot be the case that the deleted node is
## is a descendent of the root always through
## first children, since this would mean the deleted
## node is the leftmost placeholder, which
## cannot be deleted.
if deletionleftkey1_valid
while true
pparentnode = t.tree[pparent]
if pparentnode.child2 == p
t.tree[pparent] = TreeNode{K}(pparentnode.child1,
pparentnode.child2,
pparentnode.child3,
pparentnode.parent,
t.deletionleftkey[1],
pparentnode.splitkey2)
break
elseif pparentnode.child3 == p
t.tree[pparent] = TreeNode{K}(pparentnode.child1,
pparentnode.child2,
pparentnode.child3,
pparentnode.parent,
pparentnode.splitkey1,
t.deletionleftkey[1])
break
else
p = pparent
pparent = pparentnode.parent
curdepth -= 1
@invariant curdepth > 0
end
end
end
return nothing
end
|
[
655,
984
] |
function Base.delete!(t::BalancedTree23{K,D,Ord}, it::Int) where {K,D,Ord<:Ordering}
## Put the cell indexed by 'it' into the deletion list.
##
## Create the following data items maintained in the
## upcoming loop.
##
## p is a tree-node ancestor of the deleted node
## The children of p are stored in
## t.deletionchild[..]
## The number of these children is newchildcount, which is 1, 2 or 3.
## The keys that lower bound the children
## are stored in t.deletionleftkey[..]
## There is a special case for t.deletionleftkey[1]; the
## flag deletionleftkey1_valid indicates that the left key
## for the immediate right neighbor of the
## deleted node has not yet been been stored in the tree.
## Once it is stored, t.deletionleftkey[1] is no longer needed
## or used.
## The flag mustdeleteroot means that the tree has contracted
## enough that it loses a level.
p = t.data[it].parent
newchildcount = 0
c1 = t.tree[p].child1
deletionleftkey1_valid = true
if c1 != it
deletionleftkey1_valid = false
newchildcount += 1
t.deletionchild[newchildcount] = c1
t.deletionleftkey[newchildcount] = t.data[c1].k
end
c2 = t.tree[p].child2
if c2 != it
newchildcount += 1
t.deletionchild[newchildcount] = c2
t.deletionleftkey[newchildcount] = t.data[c2].k
end
c3 = t.tree[p].child3
if c3 != it && c3 > 0
newchildcount += 1
t.deletionchild[newchildcount] = c3
t.deletionleftkey[newchildcount] = t.data[c3].k
end
@invariant newchildcount == 1 || newchildcount == 2
push!(t.freedatainds, it)
pop!(t.useddatacells,it)
defaultKey = t.tree[1].splitkey1
curdepth = t.depth
mustdeleteroot = false
pparent = -1
## The following loop ascends the tree and contracts nodes (reduces their
## number of children) as
## needed. If newchildcount == 2 or 3, then the ascent is terminated
## and a node is created with 2 or 3 children.
## If newchildcount == 1, then the ascent must continue since a tree
## node cannot have one child.
while true
pparent = t.tree[p].parent
## Simple cases when the new child count is 2 or 3
if newchildcount == 2
t.tree[p] = TreeNode{K}(t.deletionchild[1],
t.deletionchild[2], 0, pparent,
t.deletionleftkey[2], defaultKey)
break
end
if newchildcount == 3
t.tree[p] = TreeNode{K}(t.deletionchild[1], t.deletionchild[2],
t.deletionchild[3], pparent,
t.deletionleftkey[2], t.deletionleftkey[3])
break
end
@invariant newchildcount == 1
## For the rest of this loop, we cover the case
## that p has one child.
## If newchildcount == 1 and curdepth==1, this means that
## the root of the tree has only one child. In this case, we can
## delete the root and make its one child the new root (see below).
if curdepth == 1
mustdeleteroot = true
break
end
## We now branch on three cases depending on whether p is child1,
## child2 or child3 of its parent.
if t.tree[pparent].child1 == p
rightsib = t.tree[pparent].child2
## Here p is child1 and rightsib is child2.
## If rightsib has 2 children, then p and
## rightsib are merged into a single node
## that has three children.
## If rightsib has 3 children, then p and
## rightsib are reformed so that each has
## two children.
if t.tree[rightsib].child3 == 0
rc1 = t.tree[rightsib].child1
rc2 = t.tree[rightsib].child2
t.tree[p] = TreeNode{K}(t.deletionchild[1],
rc1, rc2,
pparent,
t.tree[pparent].splitkey1,
t.tree[rightsib].splitkey1)
if curdepth == t.depth
replaceparent!(t.data, rc1, p)
replaceparent!(t.data, rc2, p)
else
replaceparent!(t.tree, rc1, p)
replaceparent!(t.tree, rc2, p)
end
push!(t.freetreeinds, rightsib)
newchildcount = 1
t.deletionchild[1] = p
else
rc1 = t.tree[rightsib].child1
t.tree[p] = TreeNode{K}(t.deletionchild[1], rc1, 0,
pparent,
t.tree[pparent].splitkey1,
defaultKey)
sk1 = t.tree[rightsib].splitkey1
t.tree[rightsib] = TreeNode{K}(t.tree[rightsib].child2,
t.tree[rightsib].child3,
0,
pparent,
t.tree[rightsib].splitkey2,
defaultKey)
if curdepth == t.depth
replaceparent!(t.data, rc1, p)
else
replaceparent!(t.tree, rc1, p)
end
newchildcount = 2
t.deletionchild[1] = p
t.deletionchild[2] = rightsib
t.deletionleftkey[2] = sk1
end
## If pparent had a third child (besides p and rightsib)
## then we add this to t.deletionchild
c3 = t.tree[pparent].child3
if c3 > 0
newchildcount += 1
t.deletionchild[newchildcount] = c3
t.deletionleftkey[newchildcount] = t.tree[pparent].splitkey2
end
p = pparent
elseif t.tree[pparent].child2 == p
## Here p is child2 and leftsib is child1.
## If leftsib has 2 children, then p and
## leftsib are merged into a single node
## that has three children.
## If leftsib has 3 children, then p and
## leftsib are reformed so that each has
## two children.
leftsib = t.tree[pparent].child1
lk = deletionleftkey1_valid ?
t.deletionleftkey[1] :
t.tree[pparent].splitkey1
if t.tree[leftsib].child3 == 0
lc1 = t.tree[leftsib].child1
lc2 = t.tree[leftsib].child2
t.tree[p] = TreeNode{K}(lc1, lc2,
t.deletionchild[1],
pparent,
t.tree[leftsib].splitkey1,
lk)
if curdepth == t.depth
replaceparent!(t.data, lc1, p)
replaceparent!(t.data, lc2, p)
else
replaceparent!(t.tree, lc1, p)
replaceparent!(t.tree, lc2, p)
end
push!(t.freetreeinds, leftsib)
newchildcount = 1
t.deletionchild[1] = p
else
lc3 = t.tree[leftsib].child3
t.tree[p] = TreeNode{K}(lc3, t.deletionchild[1], 0,
pparent, lk, defaultKey)
sk2 = t.tree[leftsib].splitkey2
t.tree[leftsib] = TreeNode{K}(t.tree[leftsib].child1,
t.tree[leftsib].child2,
0, pparent,
t.tree[leftsib].splitkey1,
defaultKey)
if curdepth == t.depth
replaceparent!(t.data, lc3, p)
else
replaceparent!(t.tree, lc3, p)
end
newchildcount = 2
t.deletionchild[1] = leftsib
t.deletionchild[2] = p
t.deletionleftkey[2] = sk2
end
## If pparent had a third child (besides p and leftsib)
## then we add this to t.deletionchild
c3 = t.tree[pparent].child3
if c3 > 0
newchildcount += 1
t.deletionchild[newchildcount] = c3
t.deletionleftkey[newchildcount] = t.tree[pparent].splitkey2
end
p = pparent
deletionleftkey1_valid = false
else
## Here p is child3 and leftsib is child2.
## If leftsib has 2 children, then p and
## leftsib are merged into a single node
## that has three children.
## If leftsib has 3 children, then p and
## leftsib are reformed so that each has
## two children.
@invariant t.tree[pparent].child3 == p
leftsib = t.tree[pparent].child2
lk = deletionleftkey1_valid ?
t.deletionleftkey[1] :
t.tree[pparent].splitkey2
if t.tree[leftsib].child3 == 0
lc1 = t.tree[leftsib].child1
lc2 = t.tree[leftsib].child2
t.tree[p] = TreeNode{K}(lc1, lc2,
t.deletionchild[1],
pparent,
t.tree[leftsib].splitkey1,
lk)
if curdepth == t.depth
replaceparent!(t.data, lc1, p)
replaceparent!(t.data, lc2, p)
else
replaceparent!(t.tree, lc1, p)
replaceparent!(t.tree, lc2, p)
end
push!(t.freetreeinds, leftsib)
newchildcount = 2
t.deletionchild[1] = t.tree[pparent].child1
t.deletionleftkey[2] = t.tree[pparent].splitkey1
t.deletionchild[2] = p
else
lc3 = t.tree[leftsib].child3
t.tree[p] = TreeNode{K}(lc3, t.deletionchild[1], 0,
pparent, lk, defaultKey)
sk2 = t.tree[leftsib].splitkey2
t.tree[leftsib] = TreeNode{K}(t.tree[leftsib].child1,
t.tree[leftsib].child2,
0, pparent,
t.tree[leftsib].splitkey1,
defaultKey)
if curdepth == t.depth
replaceparent!(t.data, lc3, p)
else
replaceparent!(t.tree, lc3, p)
end
newchildcount = 3
t.deletionchild[1] = t.tree[pparent].child1
t.deletionchild[2] = leftsib
t.deletionchild[3] = p
t.deletionleftkey[2] = t.tree[pparent].splitkey1
t.deletionleftkey[3] = sk2
end
p = pparent
deletionleftkey1_valid = false
end
curdepth -= 1
end
if mustdeleteroot
@invariant !deletionleftkey1_valid
@invariant p == t.rootloc
t.rootloc = t.deletionchild[1]
t.depth -= 1
push!(t.freetreeinds, p)
end
## If deletionleftkey1_valid, this means that the new
## min key of the deleted node and its right neighbors
## has never been stored in the tree. It must be stored
## as splitkey1 or splitkey2 of some ancestor of the
## deleted node, so we continue ascending the tree
## until we find a node which has p (and therefore the
## deleted node) as its descendent through its second
## or third child.
## It cannot be the case that the deleted node is
## is a descendent of the root always through
## first children, since this would mean the deleted
## node is the leftmost placeholder, which
## cannot be deleted.
if deletionleftkey1_valid
while true
pparentnode = t.tree[pparent]
if pparentnode.child2 == p
t.tree[pparent] = TreeNode{K}(pparentnode.child1,
pparentnode.child2,
pparentnode.child3,
pparentnode.parent,
t.deletionleftkey[1],
pparentnode.splitkey2)
break
elseif pparentnode.child3 == p
t.tree[pparent] = TreeNode{K}(pparentnode.child1,
pparentnode.child2,
pparentnode.child3,
pparentnode.parent,
pparentnode.splitkey1,
t.deletionleftkey[1])
break
else
p = pparent
pparent = pparentnode.parent
curdepth -= 1
@invariant curdepth > 0
end
end
end
return nothing
end
|
function Base.delete!(t::BalancedTree23{K,D,Ord}, it::Int) where {K,D,Ord<:Ordering}
## Put the cell indexed by 'it' into the deletion list.
##
## Create the following data items maintained in the
## upcoming loop.
##
## p is a tree-node ancestor of the deleted node
## The children of p are stored in
## t.deletionchild[..]
## The number of these children is newchildcount, which is 1, 2 or 3.
## The keys that lower bound the children
## are stored in t.deletionleftkey[..]
## There is a special case for t.deletionleftkey[1]; the
## flag deletionleftkey1_valid indicates that the left key
## for the immediate right neighbor of the
## deleted node has not yet been been stored in the tree.
## Once it is stored, t.deletionleftkey[1] is no longer needed
## or used.
## The flag mustdeleteroot means that the tree has contracted
## enough that it loses a level.
p = t.data[it].parent
newchildcount = 0
c1 = t.tree[p].child1
deletionleftkey1_valid = true
if c1 != it
deletionleftkey1_valid = false
newchildcount += 1
t.deletionchild[newchildcount] = c1
t.deletionleftkey[newchildcount] = t.data[c1].k
end
c2 = t.tree[p].child2
if c2 != it
newchildcount += 1
t.deletionchild[newchildcount] = c2
t.deletionleftkey[newchildcount] = t.data[c2].k
end
c3 = t.tree[p].child3
if c3 != it && c3 > 0
newchildcount += 1
t.deletionchild[newchildcount] = c3
t.deletionleftkey[newchildcount] = t.data[c3].k
end
@invariant newchildcount == 1 || newchildcount == 2
push!(t.freedatainds, it)
pop!(t.useddatacells,it)
defaultKey = t.tree[1].splitkey1
curdepth = t.depth
mustdeleteroot = false
pparent = -1
## The following loop ascends the tree and contracts nodes (reduces their
## number of children) as
## needed. If newchildcount == 2 or 3, then the ascent is terminated
## and a node is created with 2 or 3 children.
## If newchildcount == 1, then the ascent must continue since a tree
## node cannot have one child.
while true
pparent = t.tree[p].parent
## Simple cases when the new child count is 2 or 3
if newchildcount == 2
t.tree[p] = TreeNode{K}(t.deletionchild[1],
t.deletionchild[2], 0, pparent,
t.deletionleftkey[2], defaultKey)
break
end
if newchildcount == 3
t.tree[p] = TreeNode{K}(t.deletionchild[1], t.deletionchild[2],
t.deletionchild[3], pparent,
t.deletionleftkey[2], t.deletionleftkey[3])
break
end
@invariant newchildcount == 1
## For the rest of this loop, we cover the case
## that p has one child.
## If newchildcount == 1 and curdepth==1, this means that
## the root of the tree has only one child. In this case, we can
## delete the root and make its one child the new root (see below).
if curdepth == 1
mustdeleteroot = true
break
end
## We now branch on three cases depending on whether p is child1,
## child2 or child3 of its parent.
if t.tree[pparent].child1 == p
rightsib = t.tree[pparent].child2
## Here p is child1 and rightsib is child2.
## If rightsib has 2 children, then p and
## rightsib are merged into a single node
## that has three children.
## If rightsib has 3 children, then p and
## rightsib are reformed so that each has
## two children.
if t.tree[rightsib].child3 == 0
rc1 = t.tree[rightsib].child1
rc2 = t.tree[rightsib].child2
t.tree[p] = TreeNode{K}(t.deletionchild[1],
rc1, rc2,
pparent,
t.tree[pparent].splitkey1,
t.tree[rightsib].splitkey1)
if curdepth == t.depth
replaceparent!(t.data, rc1, p)
replaceparent!(t.data, rc2, p)
else
replaceparent!(t.tree, rc1, p)
replaceparent!(t.tree, rc2, p)
end
push!(t.freetreeinds, rightsib)
newchildcount = 1
t.deletionchild[1] = p
else
rc1 = t.tree[rightsib].child1
t.tree[p] = TreeNode{K}(t.deletionchild[1], rc1, 0,
pparent,
t.tree[pparent].splitkey1,
defaultKey)
sk1 = t.tree[rightsib].splitkey1
t.tree[rightsib] = TreeNode{K}(t.tree[rightsib].child2,
t.tree[rightsib].child3,
0,
pparent,
t.tree[rightsib].splitkey2,
defaultKey)
if curdepth == t.depth
replaceparent!(t.data, rc1, p)
else
replaceparent!(t.tree, rc1, p)
end
newchildcount = 2
t.deletionchild[1] = p
t.deletionchild[2] = rightsib
t.deletionleftkey[2] = sk1
end
## If pparent had a third child (besides p and rightsib)
## then we add this to t.deletionchild
c3 = t.tree[pparent].child3
if c3 > 0
newchildcount += 1
t.deletionchild[newchildcount] = c3
t.deletionleftkey[newchildcount] = t.tree[pparent].splitkey2
end
p = pparent
elseif t.tree[pparent].child2 == p
## Here p is child2 and leftsib is child1.
## If leftsib has 2 children, then p and
## leftsib are merged into a single node
## that has three children.
## If leftsib has 3 children, then p and
## leftsib are reformed so that each has
## two children.
leftsib = t.tree[pparent].child1
lk = deletionleftkey1_valid ?
t.deletionleftkey[1] :
t.tree[pparent].splitkey1
if t.tree[leftsib].child3 == 0
lc1 = t.tree[leftsib].child1
lc2 = t.tree[leftsib].child2
t.tree[p] = TreeNode{K}(lc1, lc2,
t.deletionchild[1],
pparent,
t.tree[leftsib].splitkey1,
lk)
if curdepth == t.depth
replaceparent!(t.data, lc1, p)
replaceparent!(t.data, lc2, p)
else
replaceparent!(t.tree, lc1, p)
replaceparent!(t.tree, lc2, p)
end
push!(t.freetreeinds, leftsib)
newchildcount = 1
t.deletionchild[1] = p
else
lc3 = t.tree[leftsib].child3
t.tree[p] = TreeNode{K}(lc3, t.deletionchild[1], 0,
pparent, lk, defaultKey)
sk2 = t.tree[leftsib].splitkey2
t.tree[leftsib] = TreeNode{K}(t.tree[leftsib].child1,
t.tree[leftsib].child2,
0, pparent,
t.tree[leftsib].splitkey1,
defaultKey)
if curdepth == t.depth
replaceparent!(t.data, lc3, p)
else
replaceparent!(t.tree, lc3, p)
end
newchildcount = 2
t.deletionchild[1] = leftsib
t.deletionchild[2] = p
t.deletionleftkey[2] = sk2
end
## If pparent had a third child (besides p and leftsib)
## then we add this to t.deletionchild
c3 = t.tree[pparent].child3
if c3 > 0
newchildcount += 1
t.deletionchild[newchildcount] = c3
t.deletionleftkey[newchildcount] = t.tree[pparent].splitkey2
end
p = pparent
deletionleftkey1_valid = false
else
## Here p is child3 and leftsib is child2.
## If leftsib has 2 children, then p and
## leftsib are merged into a single node
## that has three children.
## If leftsib has 3 children, then p and
## leftsib are reformed so that each has
## two children.
@invariant t.tree[pparent].child3 == p
leftsib = t.tree[pparent].child2
lk = deletionleftkey1_valid ?
t.deletionleftkey[1] :
t.tree[pparent].splitkey2
if t.tree[leftsib].child3 == 0
lc1 = t.tree[leftsib].child1
lc2 = t.tree[leftsib].child2
t.tree[p] = TreeNode{K}(lc1, lc2,
t.deletionchild[1],
pparent,
t.tree[leftsib].splitkey1,
lk)
if curdepth == t.depth
replaceparent!(t.data, lc1, p)
replaceparent!(t.data, lc2, p)
else
replaceparent!(t.tree, lc1, p)
replaceparent!(t.tree, lc2, p)
end
push!(t.freetreeinds, leftsib)
newchildcount = 2
t.deletionchild[1] = t.tree[pparent].child1
t.deletionleftkey[2] = t.tree[pparent].splitkey1
t.deletionchild[2] = p
else
lc3 = t.tree[leftsib].child3
t.tree[p] = TreeNode{K}(lc3, t.deletionchild[1], 0,
pparent, lk, defaultKey)
sk2 = t.tree[leftsib].splitkey2
t.tree[leftsib] = TreeNode{K}(t.tree[leftsib].child1,
t.tree[leftsib].child2,
0, pparent,
t.tree[leftsib].splitkey1,
defaultKey)
if curdepth == t.depth
replaceparent!(t.data, lc3, p)
else
replaceparent!(t.tree, lc3, p)
end
newchildcount = 3
t.deletionchild[1] = t.tree[pparent].child1
t.deletionchild[2] = leftsib
t.deletionchild[3] = p
t.deletionleftkey[2] = t.tree[pparent].splitkey1
t.deletionleftkey[3] = sk2
end
p = pparent
deletionleftkey1_valid = false
end
curdepth -= 1
end
if mustdeleteroot
@invariant !deletionleftkey1_valid
@invariant p == t.rootloc
t.rootloc = t.deletionchild[1]
t.depth -= 1
push!(t.freetreeinds, p)
end
## If deletionleftkey1_valid, this means that the new
## min key of the deleted node and its right neighbors
## has never been stored in the tree. It must be stored
## as splitkey1 or splitkey2 of some ancestor of the
## deleted node, so we continue ascending the tree
## until we find a node which has p (and therefore the
## deleted node) as its descendent through its second
## or third child.
## It cannot be the case that the deleted node is
## is a descendent of the root always through
## first children, since this would mean the deleted
## node is the leftmost placeholder, which
## cannot be deleted.
if deletionleftkey1_valid
while true
pparentnode = t.tree[pparent]
if pparentnode.child2 == p
t.tree[pparent] = TreeNode{K}(pparentnode.child1,
pparentnode.child2,
pparentnode.child3,
pparentnode.parent,
t.deletionleftkey[1],
pparentnode.splitkey2)
break
elseif pparentnode.child3 == p
t.tree[pparent] = TreeNode{K}(pparentnode.child1,
pparentnode.child2,
pparentnode.child3,
pparentnode.parent,
pparentnode.splitkey1,
t.deletionleftkey[1])
break
else
p = pparent
pparent = pparentnode.parent
curdepth -= 1
@invariant curdepth > 0
end
end
end
return nothing
end
|
Base.delete!
| 655
| 984
|
src/balanced_tree.jl
|
#CURRENT FILE: DataStructures.jl/src/balanced_tree.jl
##CHUNK 1
end
@inbounds thisnode = t.tree[curnode]
cmp = thisnode.child3 == 0 ?
cmp2le_leaf(t.ord, thisnode, k) :
cmp3le_leaf(t.ord, thisnode, k)
curnode = cmp == 1 ? thisnode.child1 :
cmp == 2 ? thisnode.child2 : thisnode.child3
return curnode
end
## The following are helper routines for the insert! and delete! functions.
## They replace the 'parent' field of either an internal tree node or
## a data node at the bottom tree level.
function replaceparent!(data::Vector{KDRec{K,D}}, whichind::Int, newparent::Int) where {K,D}
data[whichind] = KDRec{K,D}(newparent, data[whichind].k, data[whichind].d)
return nothing
end
##CHUNK 2
leafind, exactfound = findkey(t, k)
parent = t.data[leafind].parent
## The following code is necessary because in the case of a
## brand new tree, the initial tree and data entries were incompletely
## initialized by the constructor. In this case, the call to insert!
## underway carries
## valid K and D values, so these valid values may now be
## stored in the dummy placeholder nodes so that they no
## longer hold undefined references.
if size(t.data,1) == 2
@invariant t.rootloc == 1 && t.depth == 1
t.tree[1] = TreeNode{K}(t.tree[1].child1, t.tree[1].child2,
t.tree[1].child3, t.tree[1].parent,
k, k)
t.data[1] = KDRec{K,D}(t.data[1].parent, k, d)
t.data[2] = KDRec{K,D}(t.data[2].parent, k, d)
end
##CHUNK 3
if size(t.data,1) == 2
@invariant t.rootloc == 1 && t.depth == 1
t.tree[1] = TreeNode{K}(t.tree[1].child1, t.tree[1].child2,
t.tree[1].child3, t.tree[1].parent,
k, k)
t.data[1] = KDRec{K,D}(t.data[1].parent, k, d)
t.data[2] = KDRec{K,D}(t.data[2].parent, k, d)
end
## If we have found exactly k in the tree, then we
## replace the data associated with k and return.
if exactfound && !allowdups
t.data[leafind] = KDRec{K,D}(parent, k,d)
return false, leafind
end
# We get here if k was not already found in the tree or
# if duplicates are allowed.
##CHUNK 4
break
end
end
# If the root has been split, then we need to add a level
# to the tree that is the parent of the old root and the new node.
if splitroot
@invariant existingchild == t.rootloc
newroot = TreeNode{K}(existingchild, newchild, 0,
0, minkeynewchild, minkeynewchild)
newrootloc = push_or_reuse!(t.tree, t.freetreeinds, newroot)
replaceparent!(t.tree, existingchild, newrootloc)
replaceparent!(t.tree, newchild, newrootloc)
t.rootloc = newrootloc
t.depth += 1
end
return true, newind
end
##CHUNK 5
function findkeyless(t::BalancedTree23, k)
curnode = t.rootloc
for depthcount = 1 : t.depth - 1
@inbounds thisnode = t.tree[curnode]
cmp = thisnode.child3 == 0 ?
cmp2le_nonleaf(t.ord, thisnode, k) :
cmp3le_nonleaf(t.ord, thisnode, k)
curnode = cmp == 1 ? thisnode.child1 :
cmp == 2 ? thisnode.child2 : thisnode.child3
end
@inbounds thisnode = t.tree[curnode]
cmp = thisnode.child3 == 0 ?
cmp2le_leaf(t.ord, thisnode, k) :
cmp3le_leaf(t.ord, thisnode, k)
curnode = cmp == 1 ? thisnode.child1 :
cmp == 2 ? thisnode.child2 : thisnode.child3
return curnode
end
##CHUNK 6
# Two cases: either we need to split the tree node
# if newchild4>0 else we convert a 2-node to a 3-node
# if newchild4==0
if newchild4 == 0
# Change the parent from a 2-node to a 3-node
t.tree[p1] = TreeNode{K}(newchild1, newchild2, newchild3,
p1parent, minkeychild2, minkeychild3)
if curdepth == depth
replaceparent!(t.data, newchild, p1)
else
replaceparent!(t.tree, newchild, p1)
end
break
end
# Split the parent
t.tree[p1] = TreeNode{K}(newchild1, newchild2, 0,
p1parent, minkeychild2, minkeychild2)
newtreenode = TreeNode{K}(newchild3, newchild4, 0,
##CHUNK 7
# In this case we insert a new node.
depth = t.depth
ord = t.ord
## Store the new data item in the tree's data array. Later
## go back and fix the parent.
newind = push_or_reuse!(t.data, t.freedatainds, KDRec{K,D}(0,k,d))
push!(t.useddatacells, newind)
p1 = parent
newchild = newind
minkeynewchild = k
splitroot = false
curdepth = depth
existingchild = leafind
## This loop ascends the tree (i.e., follows the path from a leaf to the root)
## starting from the parent p1 of
## where the new key k will go.
##CHUNK 8
replaceparent!(t.data, newchild, p1)
else
replaceparent!(t.tree, newchild, p1)
end
break
end
# Split the parent
t.tree[p1] = TreeNode{K}(newchild1, newchild2, 0,
p1parent, minkeychild2, minkeychild2)
newtreenode = TreeNode{K}(newchild3, newchild4, 0,
p1parent, minkeychild4, minkeychild2)
newparentnum = push_or_reuse!(t.tree, t.freetreeinds, newtreenode)
if curdepth == depth
replaceparent!(t.data, newchild2, p1)
replaceparent!(t.data, newchild3, newparentnum)
replaceparent!(t.data, newchild4, newparentnum)
else
replaceparent!(t.tree, newchild2, p1)
replaceparent!(t.tree, newchild3, newparentnum)
replaceparent!(t.tree, newchild4, newparentnum)
##CHUNK 9
p1parent, minkeychild4, minkeychild2)
newparentnum = push_or_reuse!(t.tree, t.freetreeinds, newtreenode)
if curdepth == depth
replaceparent!(t.data, newchild2, p1)
replaceparent!(t.data, newchild3, newparentnum)
replaceparent!(t.data, newchild4, newparentnum)
else
replaceparent!(t.tree, newchild2, p1)
replaceparent!(t.tree, newchild3, newparentnum)
replaceparent!(t.tree, newchild4, newparentnum)
end
# Update the loop variables for the next level of the
# ascension
existingchild = p1
newchild = newparentnum
p1 = p1parent
minkeynewchild = minkeychild3
curdepth -= 1
if curdepth == 0
splitroot = true
##CHUNK 10
## Variables updated by the loop:
## p1: parent of where the new node goes
## newchild: index of the child to be inserted
## minkeynewchild: the minimum key in the subtree rooted at newchild
## existingchild: a child of p1; the newchild must
## be inserted in the slot to the right of existingchild
## curdepth: depth of newchild
## For each 3-node we encounter
## during the ascent, we add a new child, which requires splitting
## the 3-node into two 2-nodes. Then we keep going until we hit the root.
## If we encounter a 2-node, then the ascent can stop; we can
## change the 2-node to a 3-node with the new child.
while true
# Let newchild1,...newchild4 be the new children of
# the parent node
# Initially, take the three children of the existing parent
# node and set newchild4 to 0.
|
243
| 257
|
DataStructures.jl
| 12
|
function Base.resize!(cb::CircularBuffer, n::Integer)
if n != capacity(cb)
buf_new = Vector{eltype(cb)}(undef, n)
len_new = min(length(cb), n)
for i in 1:len_new
@inbounds buf_new[i] = cb[i]
end
cb.capacity = n
cb.first = 1
cb.length = len_new
cb.buffer = buf_new
end
return cb
end
|
function Base.resize!(cb::CircularBuffer, n::Integer)
if n != capacity(cb)
buf_new = Vector{eltype(cb)}(undef, n)
len_new = min(length(cb), n)
for i in 1:len_new
@inbounds buf_new[i] = cb[i]
end
cb.capacity = n
cb.first = 1
cb.length = len_new
cb.buffer = buf_new
end
return cb
end
|
[
243,
257
] |
function Base.resize!(cb::CircularBuffer, n::Integer)
if n != capacity(cb)
buf_new = Vector{eltype(cb)}(undef, n)
len_new = min(length(cb), n)
for i in 1:len_new
@inbounds buf_new[i] = cb[i]
end
cb.capacity = n
cb.first = 1
cb.length = len_new
cb.buffer = buf_new
end
return cb
end
|
function Base.resize!(cb::CircularBuffer, n::Integer)
if n != capacity(cb)
buf_new = Vector{eltype(cb)}(undef, n)
len_new = min(length(cb), n)
for i in 1:len_new
@inbounds buf_new[i] = cb[i]
end
cb.capacity = n
cb.first = 1
cb.length = len_new
cb.buffer = buf_new
end
return cb
end
|
Base.resize!
| 243
| 257
|
src/circular_buffer.jl
|
#FILE: DataStructures.jl/src/circ_deque.jl
##CHUNK 1
Create a double-ended queue of maximum capacity `n`, implemented as a circular buffer. The element type is `T`.
"""
CircularDeque{T}(n::Int) where {T} = CircularDeque(Vector{T}(undef, n), n, 0, 1, n)
CircularDeque{T}(n::Integer) where {T} = CircularDeque(Vector{T}(undef, Int(n)), Int(n), 0, 1, Int(n))
Base.length(D::CircularDeque) = D.n
Base.eltype(::Type{CircularDeque{T}}) where {T} = T
"""
capacity(D::CircularDeque)
Return the capacity of the circular deque
"""
capacity(D::CircularDeque) = D.capacity
function Base.empty!(D::CircularDeque)
D.n = 0
D.first = 1
D.last = D.capacity
#CURRENT FILE: DataStructures.jl/src/circular_buffer.jl
##CHUNK 1
Get the first element of CircularBuffer.
"""
Base.@propagate_inbounds function Base.first(cb::CircularBuffer)
@boundscheck (cb.length == 0) && throw(BoundsError(cb, 1))
return cb.buffer[cb.first]
end
"""
last(cb::CircularBuffer)
Get the last element of CircularBuffer.
"""
Base.@propagate_inbounds function Base.last(cb::CircularBuffer)
@boundscheck (cb.length == 0) && throw(BoundsError(cb, 1))
return cb.buffer[_buffer_index(cb, cb.length)]
end
"""
resize!(cb::CircularBuffer, n)
Resize CircularBuffer to the maximum capacity of n elements.
##CHUNK 2
"""
Base.@propagate_inbounds function Base.last(cb::CircularBuffer)
@boundscheck (cb.length == 0) && throw(BoundsError(cb, 1))
return cb.buffer[_buffer_index(cb, cb.length)]
end
"""
resize!(cb::CircularBuffer, n)
Resize CircularBuffer to the maximum capacity of n elements.
If n is smaller than the current buffer length, the first n elements will be retained.
"""
##CHUNK 3
function Base.pushfirst!(cb::CircularBuffer, data)
# if full, decrement and overwrite, otherwise pushfirst
cb.first = (cb.first == 1 ? cb.capacity : cb.first - 1)
if length(cb) < cb.capacity
cb.length += 1
end
@inbounds cb.buffer[cb.first] = data
return cb
end
"""
append!(cb::CircularBuffer, datavec::AbstractVector)
Push at most last `capacity` items.
"""
function Base.append!(cb::CircularBuffer, datavec::AbstractVector)
# push at most last `capacity` items
n = length(datavec)
for i in max(1, n-capacity(cb)+1):n
push!(cb, datavec[i])
##CHUNK 4
function Base.fill!(cb::CircularBuffer, data)
for i in 1:capacity(cb)-length(cb)
push!(cb, data)
end
return cb
end
"""
length(cb::CircularBuffer)
Return the number of elements currently in the buffer.
"""
Base.length(cb::CircularBuffer) = cb.length
"""
size(cb::CircularBuffer)
Return a tuple with the size of the buffer.
"""
Base.size(cb::CircularBuffer) = (length(cb),)
##CHUNK 5
cb.length -= 1
return @inbounds cb.buffer[i]
end
"""
pushfirst!(cb::CircularBuffer, data)
Insert one or more items at the beginning of CircularBuffer
and overwrite back if full.
"""
function Base.pushfirst!(cb::CircularBuffer, data)
# if full, decrement and overwrite, otherwise pushfirst
cb.first = (cb.first == 1 ? cb.capacity : cb.first - 1)
if length(cb) < cb.capacity
cb.length += 1
end
@inbounds cb.buffer[cb.first] = data
return cb
end
##CHUNK 6
# if full, increment and overwrite, otherwise push
if cb.length == cb.capacity
cb.first = (cb.first == cb.capacity ? 1 : cb.first + 1)
else
cb.length += 1
end
@inbounds cb.buffer[_buffer_index(cb, cb.length)] = data_converted
return cb
end
"""
popfirst!(cb::CircularBuffer)
Remove the element from the front of the `CircularBuffer`.
"""
function Base.popfirst!(cb::CircularBuffer)
@boundscheck (cb.length == 0) && throw(ArgumentError("array must be non-empty"))
i = cb.first
cb.first = (cb.first + 1 > cb.capacity ? 1 : cb.first + 1)
##CHUNK 7
end
CircularBuffer(iter) = CircularBuffer{eltype(iter)}(iter)
"""
empty!(cb::CircularBuffer)
Reset the buffer.
"""
function Base.empty!(cb::CircularBuffer)
cb.length = 0
return cb
end
Base.@propagate_inbounds function _buffer_index_checked(cb::CircularBuffer, i::Int)
@boundscheck if i < 1 || i > cb.length
throw(BoundsError(cb, i))
end
_buffer_index(cb, i)
end
##CHUNK 8
end
return cb
end
"""
fill!(cb::CircularBuffer, data)
Grows the buffer up-to capacity, and fills it entirely.
It doesn't overwrite existing elements.
"""
function Base.fill!(cb::CircularBuffer, data)
for i in 1:capacity(cb)-length(cb)
push!(cb, data)
end
return cb
end
"""
length(cb::CircularBuffer)
##CHUNK 9
"""
append!(cb::CircularBuffer, datavec::AbstractVector)
Push at most last `capacity` items.
"""
function Base.append!(cb::CircularBuffer, datavec::AbstractVector)
# push at most last `capacity` items
n = length(datavec)
for i in max(1, n-capacity(cb)+1):n
push!(cb, datavec[i])
end
return cb
end
"""
fill!(cb::CircularBuffer, data)
Grows the buffer up-to capacity, and fills it entirely.
It doesn't overwrite existing elements.
"""
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 11