forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add Fenwick Tree (Binary Index Tree)
- Loading branch information
Sarot Busala
authored
Oct 20, 2017
1 parent
535cbb7
commit d68d0ef
Showing
1 changed file
with
28 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
class FenwickTree: | ||
|
||
def __init__(self, SIZE): # create fenwick tree with size SIZE | ||
self.Size = SIZE | ||
self.ft = [0 for i in range (0,SIZE)] | ||
|
||
def update(self, i, val): # update data (adding) in index i in O(lg N) | ||
while (i < self.Size): | ||
self.ft[i] += val | ||
i += i & (-i) | ||
|
||
def query(self, i): # query cumulative data from index 0 to i in O(lg N) | ||
ret = 0 | ||
while (i > 0): | ||
ret += self.ft[i] | ||
i -= i & (-i) | ||
return ret | ||
|
||
if __name__ == '__main__': | ||
f = FenwickTree(100) | ||
f.update(1,20) | ||
f.update(4,4) | ||
print (f.query(1)) | ||
print (f.query(3)) | ||
print (f.query(4)) | ||
f.update(2,-5) | ||
print (f.query(1)) | ||
print (f.query(3)) |