0% found this document useful (0 votes)
26 views10 pages

ADS 0256 EXP 7

Uploaded by

samanthaargent21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views10 pages

ADS 0256 EXP 7

Uploaded by

samanthaargent21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Academic Year 2024-25 SAP ID: 60003220256

DEPARTMENT OF INFORMATION TECHNOLOGY


COURSE CODE: DATE: 14-10-24
COURSE NAME: Advanced Data Structures Laboratory CLASS: TE-IT
Name: Rutuja Visale SAP: 60003220256
Div: IT3-1
LAB EXPERIMENT NO. 07
CO/LO: CO2 – Solve a problem using appropriate data structure.

AIM / OBJECTIVE: To implement Segment Tree.

THEORY:
o The leaf nodes represent elements of the array.
o Internal nodes of the tree are generated by merging their child nodes. Since we are using

an array to represent a segment tree, a node sitting at index j has the left child at 2 * j + 1
and right child at 2 * j + 2, and the parent of the node at the index j is ⌊(j - 1) / 2⌋.
Thus, for the array a[] = {2, 4, 7, 10, 12, 13}, the representation of segment tree as an array will
be:
segArr[] = {48, 13, 35, 6, 7, 22, 13, 2, 4, k, k, 10, 12, k, k}; where k is a dummy value. The
dummy values are of no use. In fact, it is the wastage of some space because of the array
representation. The segment tree will be:
Academic Year 2024-25 SAP ID: 60003220256

Segment Tree is a basically a binary tree used for storing the intervals or segments. Each node in
the Segment Tree represents an interval Consider an array A of size N and a corresponding
Segment Tree T
 The root of T will represent the whole array A0N-1
 Each leaf in the Segment Tree T will represent a single element A[i] such that 0≤1< N.
 The internal nodes in the Segment Tree represents the union of elementary intervals
A[I:j] where 0 ≤1< N.

The root of the Segment Tree represents the whole array A[0:N-1]. Then it is broken down into
two half intervals or segments and the two children of the root in turn represent the A[0: (N-1)/2]
and A[(N-1)/2+1: (N-1)]. So in each step, the segment is divided into half and the two children
represent those two halves. So the height of the segment tree will be log2N. There are N leaves
representing the N elements of the array. The number of internal nodes is N-1 so a total number
of nodes are 2*N-1.
Once the Segment Tree is built its structure cannot be changed. We can update the values of
nodes but we cannot change its structure.

Building Tree: in this step, we create the structure of the segment tree variable and initialize it
Updating Tree: during this step, we change the tree by updating the value in the array at a point
or over an interval
Querying Tree: we may use this operation to run a range query on the array

In a Segment Tree, the array is stored at the leaves of the tree, while the internal nodes store
information about segments represented by its children. The internal nodes are formed in a
bottom- up manner by merging the information from its child nodes.

Segment Trees are useful whenever we’re frequently working with ranges of numerical data. In
this context, let’s look at an example to better understand the Segment Tree by describing each
step. We want to construct a Segment Tree array that allows us to find the sum of the elements in
an array.
Academic Year 2024-25 SAP ID: 60003220256

Consider an array A = [1, 2, 1, 8, 7]

 The root node is represented by A[0,n-1] which stores the sum of all the elements of the
given array.
 Then the segment A[0,n-1] is divided into two halves, namely A[0,n/2] and A[n/2+1,n-
1], and the sum of each half is computed and stored.
 Each of these two halves is further split into half, and the sum is computed and stored.
 This process continues until all the segments length becomes 1.
 So, at the first level, there is one node that is the root. In the second level, there are two
nodes, third level four nodes, until the number of nodes in a level becomes n.
 All the leaf nodes represent the individual elements of the array. As you can see in the
above segment tree, the highlighted sums are nothing but the element at that index.

Applications
 Computational geometry.
 Geographic information systems.
 Machine learning.
Academic Year 2024-25 SAP ID: 60003220256

 In its early days, the Segment Tree was used to efficiently list all pairs of intersecting
rectangles from a list of rectangles in the plane.
 We can use this method to report the list of all rectilinear line segments in the plane
which intersect a query line segment.
 We use this technique to report the perimeter of a set of rectangles in the plane.
 More recently, the segment tree has become popular for use in pattern recognition and
image processing.
 Finding range sum/product, range max/min, prefix sum/product, etc.

Properties of Segment Tree


 The height of the segment tree is O(log n) because while moving from the root to the
leaves at every level, the length of the segments is reduced by half.
 The total number of levels is log n and starting from one node at the first level, the
number of nodes gets doubled at every level.
ALGORITHM:
Building Segment tree:
1. Define the root of the segment tree.
2. We have array A and the start and end indices as L=0 and R=n-1.
3. Now, let’s define a recursive function build() which takes as parameters the given array,
current root, start index L and end index R of the interval.
4. For the current root, initialize its interval with L and R values.
5. Check if L==R. If so, then it means it is a leaf node, so the sum value of the current node
will be A[L], i.e. array element at index L.
6. If L is not equal to R, then call the build() function recursively for the left and right children
of current. Then, initialize the sum value of the current node as the sum of its left and right
children.
Academic Year 2024-25 SAP ID: 60003220256

Code:
class SegmentTree {
class Node {
int min;
int max;
int sum;
public Node(int min, int max, int sum) {
this.min = min;
this.max = max;
this.sum = sum;
}
}

Node[] segmentTree;
int n;

public SegmentTree(int[] arr) {


this.n = arr.length;

segmentTree = new Node[4 * n];


build(arr, 0, 0, n - 1);
}

private void build(int[] arr, int node, int start, int end) {
if (start == end) {

segmentTree[node] = new Node(arr[start], arr[start], arr[start]);


} else {
int mid = (start + end) / 2;

build(arr, 2 * node + 1, start, mid);


build(arr, 2 * node + 2, mid + 1, end);
Academic Year 2024-25 SAP ID: 60003220256

segmentTree[node] = mergeNodes(segmentTree[2 * node + 1], segmentTree[2 * node +


2]);
}
}
private Node mergeNodes(Node left, Node right) {
return new Node(
Math.min(left.min, right.min),
Math.max(left.max, right.max),
left.sum + right.sum
);
}

public Node query(int L, int R) {


return query(0, 0, n - 1, L, R);
}

private Node query(int node, int start, int end, int L, int R) {
if (R < start || L > end) {
return new Node(Integer.MAX_VALUE, Integer.MIN_VALUE, 0);
}
if (L <= start && end <= R) {
return segmentTree[node];
}
int mid = (start + end) / 2;
Node leftResult = query(2 * node + 1, start, mid, L, R);
Node rightResult = query(2 * node + 2, mid + 1, end, L, R);

return mergeNodes(leftResult, rightResult);


}

public void update(int index, int value) {


update(0, 0, n - 1, index, value);
}
Academic Year 2024-25 SAP ID: 60003220256

private void update(int node, int start, int end, int index, int value) {
if (start == end) {

segmentTree[node] = new Node(value, value, value);


} else {
int mid = (start + end) / 2;
if (index <= mid) {
update(2 * node + 1, start, mid, index, value);
} else {
update(2 * node + 2, mid + 1, end, index, value);
}
segmentTree[node] = mergeNodes(segmentTree[2 * node + 1], segmentTree[2 * node +
2]);
}
}
public void printSegmentTree()
{ for (int i = 0; i < 4 * n; i++)
{
if (segmentTree[i] != null) {
System.out.println("Node " + i + " => Min: " + segmentTree[i].min + ", Max: " +
segmentTree[i].max + ", Sum: " + segmentTree[i].sum);
}
}
}
public static void main(String[] args)
{ int[] arr = {1, 3, 5, 7, 9, 11};
SegmentTree st = new SegmentTree(arr);

System.out.println("Initial Segment Tree:");


st.printSegmentTree();

System.out.println("Range [1, 3]: ");


Academic Year 2024-25 SAP ID: 60003220256

Node result = st.query(1, 3);


Academic Year 2024-25 SAP ID: 60003220256

System.out.println("Min: " + result.min + ", Max: " + result.max + ", Sum: " + result.sum);

System.out.println("Range [0, 5]: ");


result = st.query(0, 5);
System.out.println("Min: " + result.min + ", Max: " + result.max + ", Sum: " + result.sum);

System.out.println("Updating index 1 to 10...");


st.update(1, 10);

System.out.println("Updated Segment Tree:");


st.printSegmentTree();

System.out.println("Range [1, 3]: ");


result = st.query(1, 3);
System.out.println("Min: " + result.min + ", Max: " + result.max + ", Sum: " + result.sum);
}
}
Output:
Academic Year 2024-25 SAP ID: 60003220256

CONCLUSION:
 Used for efficiently solving problems involving range query operations.
 A divide and conquer algorithm.
 Time Complexity for tree construction is O(n).
 Time complexity for querying and updation are O(log n).
 Applicable where pre-computation fails or is costly.
 Alternatives to segment tree are Binary Indexed Tree and SQRT tree.

We learned what a Segment Tree is, and why do we need one. We also implemented it in C++ and
discussed about the applications.

BOOKS AND WEB RESOURCES:

1. Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, “Introduction to


Algorithms”, 3rd Edition, The MIT Press, 2009.
2. PowerPoint Slides of Segment Tree

Website References:
[1] https://www.scaler.com/topics/data-structures/segment-trees-in-data-structure/
[2] https://www.baeldung.com/cs/segment-tree

You might also like