MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / NewFenwickTree

Function NewFenwickTree

structure/fenwicktree/fenwicktree.go:20–34  ·  view source on GitHub ↗

NewFenwickTree creates a new Fenwick tree, initializes bit with the values of the array. Note that the queries and updates should have one based indexing.

(array []int)

Source from the content-addressed store, hash-verified

18// the values of the array. Note that the queries and updates should have
19// one based indexing.
20func NewFenwickTree(array []int) *FenwickTree {
21 newArray := []int{0} // Appending a 0 to the beginning as this implementation uses 1 based indexing
22 fenwickTree := &FenwickTree{
23 n: len(array),
24 array: append(newArray, array...),
25 bit: append(newArray, array...),
26 }
27 for i := 1; i < fenwickTree.n; i++ {
28 nextPos := i + (i & -i)
29 if nextPos <= fenwickTree.n {
30 fenwickTree.bit[nextPos] += fenwickTree.bit[i]
31 }
32 }
33 return fenwickTree
34}
35
36// PrefixSum returns the sum of the prefix ending at position pos.
37func (f *FenwickTree) PrefixSum(pos int) int {

Callers 1

TestFenwickTreeFunction · 0.92

Calls

no outgoing calls

Tested by 1

TestFenwickTreeFunction · 0.74