File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments