<script>
// Javascript program to implement
// iterative segment tree.
function construct_segment_tree(segtree, a, n)
{
// Assign values to leaves of the segment tree
for(let i = 0; i < n; i++)
segtree[n + i] = a[i];
// Assign values to internal nodes
// to compute maximum in a given range
for(let i = n - 1; i >= 1; i--)
segtree[i] = Math.max(segtree[2 * i],
segtree[2 * i + 1]);
}
function update(segtree, pos, value, n)
{
// Change the index to leaf node first
pos += n;
// Update the value at the leaf node
// at the exact index
segtree[pos] = value;
while (pos > 1)
{
// Move up one level at a time in the tree
pos >>= 1;
// Update the values in the nodes in
// the next higher level
segtree[pos] = Math.max(segtree[2 * pos],
segtree[2 * pos + 1]);
}
}
function range_query(segtree, left, right, n)
{
/* Basically the left and right indices will move
towards right and left respectively and with
every each next higher level and compute the
maximum at each height. */
// change the index to leaf node first
left += n;
right += n;
// Initialize maximum to a very low value
let ma = Number.MIN_VALUE;
while (left < right)
{
// If left index in odd
if ((left & 1) != 0)
{
ma = Math.max(ma, segtree[left]);
// Make left index even
left++;
}
// If right index in odd
if ((right & 1) > 0)
{
// Make right index even
right--;
ma = Math.max(ma, segtree[right]);
}
// Move to the next higher level
left = parseInt(left / 2, 10);
right = parseInt(right / 2, 10);
}
return ma;
}
// Driver code
let a = [ 2, 6, 10, 4, 7, 28, 9, 11, 6, 33 ];
let n = a.length;
// Construct the segment tree by assigning
// the values to the internal nodes
let segtree = new Array(2 * n);
construct_segment_tree(segtree, a, n);
// Compute maximum in the range left to right
let left = 1, right = 5;
document.write("Maximum in range " + left +
" to " + right + " is " +
range_query(segtree, left, right + 1, n) + "</br>");
// Update the value of index 5 to 32
let index = 5, value = 32;
// a[5] = 32;
// Contents of array : {2, 6, 10, 4, 7, 32, 9, 11, 6, 33}
update(segtree, index, value, n);
// Compute maximum in the range left to right
left = 2, right = 8;
document.write("Maximum in range " + left +
" to " + right + " is " +
range_query(segtree, left, right + 1, n) + "</br>");
// This code is contributed by divyesh072019
</script>