From facd091b1ec5b66b1b337c3b0b0e67848c649715 Mon Sep 17 00:00:00 2001 From: Ananya Chaurasia <65891617+Ananya88@users.noreply.github.com> Date: Sat, 15 Aug 2020 15:39:17 +0530 Subject: [PATCH] Create Fenwick tree or Binary indexed tree --- algos/Fenwick tree or Binary indexed tree | 75 +++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 algos/Fenwick tree or Binary indexed tree diff --git a/algos/Fenwick tree or Binary indexed tree b/algos/Fenwick tree or Binary indexed tree new file mode 100644 index 0000000..5a12519 --- /dev/null +++ b/algos/Fenwick tree or Binary indexed tree @@ -0,0 +1,75 @@ +#include +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; + int freq[n]; + for(int i=0;i>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) " <