SegmentTree v0.1.0 SegmentTree View Source
Data structure to compute efficiently operation on ranges.
Problem
Given a range [0, n-1] of n values, we want to efficiently calculate an operation (e.g. sum), a naive approach is to iterate through a list but we will get the answer in O(n) time.
list = [a, b, ..., z]
list_cut = cut(list, k, n)
sum = Enum.sum(list_cut)
If many random ranges must be computed on this list we can use a more efficient approach using SegmentTree
segment_tree = SegmentTree.new(n, &Kernel.+/2)
segment_tree = populate(segment_tree, list)
sum = SegmentTree.aggregate(segment_tree, k, n)
We will then be able to get an answer in O(log(n)) time.
Link to this section Summary
Functions
Compute range value of a SegmentTree between min and max
Create a new SegmentTree structure
Insert element in SegmentTree at the given index
Link to this section Types
Link to this section Functions
Link to this function
aggregate(segment_tree, range_min, range_max)
View Source
aggregate(SegmentTree.t(), non_neg_integer(), non_neg_integer()) :: term()
Compute range value of a SegmentTree between min and max
Examples
SegmentTree.aggregate(%SegmentTree{...}, 10, 29)
#=> %SegmentTree{...}
Link to this function
new(max_index, aggregate_fun, default \\ 0)
View Source
new(non_neg_integer(), (term(), term() -> term()), term()) :: SegmentTree.t()
Create a new SegmentTree structure
max_index must be higher than any index used in the range
Examples
SegmentTree.new(1_000, &Kernel.+/2)
#=> %SegmentTree{default: 0, tree: %{}, aggregate_fun: &Kernel.+/2, max_index: 1_023}
Link to this function
put(segment_tree, index, value)
View Source
put(SegmentTree.t(), non_neg_integer(), term()) :: SegmentTree.t()
Insert element in SegmentTree at the given index
Examples
SegmentTree.put(%SegmentTree{...}, 10, 29)
#=> %SegmentTree{...}