Skip to content

Commit 4a2b190

Browse files
Add Fenwick Tree (TheAlgorithms#2570)
1 parent 68d6a94 commit 4a2b190

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package DataStructures.Trees;
2+
3+
public class FenwickTree {
4+
private int n;
5+
private int fen_t[];
6+
7+
/* Constructor which takes the size of the array as a parameter */
8+
public FenwickTree(int n) {
9+
this.n = n;
10+
this.fen_t = new int[n + 1];
11+
}
12+
13+
/* A function which will add the element val at index i*/
14+
public void update(int i, int val) {
15+
// As index starts from 0, increment the index by 1
16+
i += 1;
17+
while (i <= n) {
18+
fen_t[i] += val;
19+
i += i & (-i);
20+
}
21+
}
22+
23+
/* A function which will return the cumulative sum from index 1 to index i*/
24+
public int query(int i) {
25+
// As index starts from 0, increment the index by 1
26+
i += 1;
27+
int cumSum = 0;
28+
while (i > 0) {
29+
cumSum += fen_t[i];
30+
i -= i & (-i);
31+
}
32+
return cumSum;
33+
}
34+
}

0 commit comments

Comments
 (0)