Skip to content

Commit 50eeaed

Browse files
committed
implement rank, to complete order-statistics using AVLTree
1 parent 5785868 commit 50eeaed

File tree

4 files changed

+36
-1
lines changed

4 files changed

+36
-1
lines changed

docs/src/avl_tree.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ julia> for k in 1:2:10
2727
2828
julia> haskey(tree, 5)
2929
false
30+
31+
julia> rank(tree, 17)
32+
4
3033
```
3134

3235
```@meta

src/DataStructures.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ module DataStructures
6060
export DiBitVector
6161

6262
export RBTree, search_node, minimum_node
63-
export AVLTree
63+
export AVLTree, rank
6464

6565
export findkey
6666

src/avl_tree.jl

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,27 @@ function Base.delete!(tree::AVLTree{K}, d::K) where K
228228
return tree
229229
end
230230

231+
"""
232+
rank(tree::AVLTree, key)
233+
234+
Returns the rank of `key` present in the `tree`, if it present. A KeyError is thrown if `key` is not present.
235+
"""
236+
function rank(tree::AVLTree{K}, key::K) where K
237+
!haskey(tree, key) && throw(KeyError(key))
238+
node = tree.root
239+
rank = 0
240+
while node.data != key
241+
if (node.data < key)
242+
rank += (1 + get_subsize(node.leftChild))
243+
node = node.rightChild
244+
else
245+
node = node.leftChild
246+
end
247+
end
248+
rank += (1 + get_subsize(node.leftChild))
249+
return rank
250+
end
251+
231252
function Base.getindex(tree::AVLTree{K}, ind::Integer) where K
232253
@boundscheck (1 <= ind <= tree.count) || throw(BoundsError("$ind should be in between 1 and $(tree.count)"))
233254
function traverse_tree(node::AVLTreeNode_or_null, idx)

test/test_avl_tree.jl

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,4 +131,15 @@
131131
node = node.leftChild
132132
end
133133
end
134+
135+
@testset "rank" begin
136+
t9 = AVLTree{Int}()
137+
for i in 1:20
138+
push!(t9, i)
139+
end
140+
for i in 1:20
141+
@test rank(t9, i) == i
142+
end
143+
@test_throws KeyError rank(t9, 21)
144+
end
134145
end

0 commit comments

Comments
 (0)