|
5 | 5 | */
|
6 | 6 |
|
7 | 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 |
| - } |
| 8 | + /** |
| 9 | + * Constructs a Fenwick Tree. |
| 10 | + * @param {Array} fenwickArray The Fenwick Tree array to be initialized. |
| 11 | + * @param {Array} array The input array whose prefix sum is to be calculated. |
| 12 | + * @param {number} n The size of the input array. |
| 13 | + */ |
| 14 | + constructor(feneickArray, array, n) { |
| 15 | + for (let i = 1; i <= n; i++) { |
| 16 | + feneickArray[i] = 0 |
| 17 | + } |
| 18 | + for (let i = 0; i < n; i++) { |
| 19 | + this.update(feneickArray, n, i, array[i]) |
| 20 | + } |
| 21 | + } |
16 | 22 |
|
17 |
| - update(feneickArray, n, index, value) { |
18 |
| - index = index + 1 |
19 |
| - while (index <= n) { |
20 |
| - feneickArray[index] += value |
21 |
| - index += index & -index |
22 |
| - } |
23 |
| - } |
| 23 | + /** |
| 24 | + * Updates the Fenwick Tree with a new value at the specified index. |
| 25 | + * @param {Array} fenwickArray The Fenwick Tree array. |
| 26 | + * @param {number} n The size of the Fenwick Tree array. |
| 27 | + * @param {number} index The index at which the value is updated. |
| 28 | + * @param {number} value The new value to be added at the index. |
| 29 | + */ |
| 30 | + update(feneickArray, n, index, value) { |
| 31 | + index = index + 1 |
| 32 | + while (index <= n) { |
| 33 | + feneickArray[index] += value |
| 34 | + index += index & -index |
| 35 | + } |
| 36 | + } |
24 | 37 |
|
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 |
| - } |
| 38 | + getPrefixSum(feneickArray, index) { |
| 39 | + let currSum = 0 |
| 40 | + index = index + 1 |
| 41 | + while (index > 0) { |
| 42 | + currSum += feneickArray[index] |
| 43 | + index -= index & -index |
| 44 | + } |
32 | 45 |
|
33 |
| - return currSum |
34 |
| - } |
| 46 | + return currSum |
| 47 | + } |
35 | 48 | }
|
36 | 49 | export { FenwickTree }
|
0 commit comments