Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions algos/Fenwick tree or Binary indexed tree
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#include<bits/stdc++.h>
using namespace std;

int getSum(int BITree[], int index)
{
int sum = 0; // Iniialize result

// index in BITree[] is 1 more than the index in arr[]
index = index + 1;

// Traverse ancestors of BITree[index]
while (index>0)
{
// Add current element of BITree to sum
sum += BITree[index];

// Move index to parent node in getSum View
index -= index & (-index);
}
return sum;
}

// Updates a node in Binary Index Tree (BITree) at given index
void updateBIT(int BITree[], int n, int index, int val)
{
// index in BITree[] is 1 more than the index in arr[]
index = index + 1;


while (index <= n)
{
// Add 'val' to current node of BI Tree
BITree[index] += val;

// Update index to that of parent in update View
index += index & (-index);
}
}

int *constructBITree(int arr[], int n)
{

int *BITree = new int[n+1];
for (int i=1; i<=n; i++)
BITree[i] = 0;

// Store the actual values in BITree[] using update()
for (int i=0; i<n; i++)
updateBIT(BITree, n, i, arr[i]);

return BITree;
}

//main function
int main()
{
int n;
cin>>n;
int freq[n];
for(int i=0;i<n;i++){
cin>>freq[i];
}

int *BITree = constructBITree(freq, n);
cout << "Sum of elements "
<< getSum(BITree, 5)<<'\n';


freq[3] += 6;
updateBIT(BITree, n, 3, 6); //Update BIT for above change in arr[]

cout << "Sum of elements (after update) " <<getSum(BITree, 5);

return 0;
}