-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBinaryIndexedTree.cs
More file actions
64 lines (49 loc) · 1.52 KB
/
Copy pathBinaryIndexedTree.cs
File metadata and controls
64 lines (49 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
namespace AlgorithmsAndDataStructures.DataStructures.BinaryIndexedTrees;
public class BinaryIndexedTree
{
private readonly int[] binaryIndexedTree;
private readonly int treeSize;
public BinaryIndexedTree(int treeSize = 100)
{
this.treeSize = treeSize;
binaryIndexedTree = new int[this.treeSize];
}
public static BinaryIndexedTree FromArray(int[] input)
{
if (input is null) return null;
var result = new BinaryIndexedTree(input.Length + 1);
var index = 0;
foreach (var item in input)
{
result.SetValue(index, item);
index++;
}
return result;
}
public int GetSum(int index)
{
// Since range in Fenwick tree doesn't include last element
var currentIndex = index + 1;
var result = 0;
while (currentIndex > 0)
{
result += binaryIndexedTree[currentIndex];
//TRICK: parent of any node can be obtain by removing the last set bit from the binary representation of that node.
currentIndex -= currentIndex & -currentIndex;
}
return result;
}
public int GetSum(int start, int end)
{
return GetSum(end) - GetSum(start - 1);
}
public void SetValue(int index, int value)
{
var currentIndex = index + 1;
while (currentIndex < treeSize)
{
binaryIndexedTree[currentIndex] += value;
currentIndex += currentIndex & -currentIndex;
}
}
}