Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c3b2bac

Browse files
merge: fixes: #{} (#853)
* fixes: #{} * fixes : ISSUE#795 * Fixed ISSUE:795 * Fixed : ISSUE:795 * Fixed ISSUE : 795 * Fixed ISSUE : 795
1 parent bf681d1 commit c3b2bac

File tree

3 files changed

+11524
-563
lines changed

3 files changed

+11524
-563
lines changed

‎Trees/FenwickTree.js‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
* Author: Mohit Kumar
3+
* Fedwick Tree Implementation in JavaScript
4+
* Fedwick Tree Implementation for finding prefix sum.
5+
*/
6+
7+
class FenwickTree {
8+
constructor (feneickArray, array, n) {
9+
for (let i = 1; i <= n; i++) {
10+
feneickArray[i] = 0
11+
}
12+
for (let i = 0; i < n; i++) {
13+
this.update(feneickArray, n, i, array[i])
14+
}
15+
}
16+
17+
update (feneickArray, n, index, value) {
18+
index = index + 1
19+
while (index <= n) {
20+
feneickArray[index] += value
21+
index += index & (-index)
22+
}
23+
}
24+
25+
getPrefixSum (feneickArray, index) {
26+
let currSum = 0
27+
index = index + 1
28+
while (index > 0) {
29+
currSum += feneickArray[index]
30+
index -= index & (-index)
31+
}
32+
33+
return currSum
34+
}
35+
}
36+
export { FenwickTree }

‎Trees/test/FenwickTree.test.js‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { FenwickTree } from '../FenwickTree'
2+
3+
describe('Fenwick Tree Implementation', () => {
4+
const fenwickArray = new Array(1000)
5+
const array = [3, 2, 0, 6, 5, -1, 2]
6+
const length = array.length
7+
8+
const fenwickTree = new FenwickTree(fenwickArray, array, length)
9+
10+
it('Fenwick Tree - Prefix sum of array', () => {
11+
const prefixSum = fenwickTree.getPrefixSum(fenwickArray, 6)
12+
expect(prefixSum).toBe(23)
13+
})
14+
15+
array[2] += 6
16+
fenwickTree.update(fenwickArray, length, 2, 6)
17+
18+
it('Fenwick Tree - Prefix sum of Updated array', () => {
19+
const prefixSum = fenwickTree.getPrefixSum(fenwickArray, 6)
20+
expect(prefixSum).toBe(23)
21+
})
22+
})

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /