×

Segment Tree in Java

Binary trees can address a variety of issues; however, the Segment Tree is more efficient in terms of time complexity. The segment tree in Java is represented using an array.

Native Approach

 It is simple to complete these activities. One may compute the cumulative sum of the elements located between index x and index y by running a for-loop from x to y. When we look at how long it will take to get the total, we obtain O(n) time.

A[j] = p can also be used to update the value at the j-th index, and this operation takes O(1) time. As a result, the total time complexity to do both tasks is O(n) + O(1) = O (n).

Other Approach

The alternative strategy is to first make a prefix array, then finish the aforementioned activities. The sum of the items from index x to index y requires O(1) time once the prefix array has been created. However, it will now take O(n) time to update the jth index. This is due to the fact that updating any index requires updating the prefix array, which takes O(1) time. It follows that the total time complexity is O(1) + O(n) = O(n), which is identical to the naïve method. Since both ways take the same amount of time overall, we must find a way to make it take less time, and the solution is to use a segment tree. The sum from index x to index y is computed in the segment tree in O(log(n)) time. The segment tree requires an O(log(n)) amount of time to update the value at the jth index. O(log(n)) + O(log(n)) = O(2 *(log(n)), which is smaller than O, is the result (n).

Segment Tree Representation

The array's elements are represented by the leaf nodes. By combining their child nodes, the internal nodes of the tree are produced. A node at index j has a left child at 2 * j + 1, a right child at 2 * j + 2, and a parent at (j - 1) / 2 since we are using an array to represent the segment tree.

Pseudo Code for Segment Tree

The difficulty is utilizing the segment tree to compute the total after the segment tree has been built.

int Sum1(node, a, b)   
{  
   if (the range of the node is within a and b)  
{
                  return value of the node  


}
   else if (the range of the node is outside of a and b)  
        return 0  
   else  
    return Sum1(node left child, a, b) +   
           getSum1(node right child, a, b)  
}  

Updation of Value

Recursive updating is used in segment tree operations. Assume that the value of the j-th index is val and that it has to be changed. Add the value val to all the nodes in the segment tree whose range includes the specified range, starting at the root. One should avoid making any modifications to a node if the range of that node does not contain the specified index.

Program for Segment tree using Java

SegmentTree.java

public class SegmentTree
{  
int stArray[];
SegmentTree(int var[], int s1)  
{  
int height = (int) (Math.ceil(Math.log(s1) / Math.log(2)));  
int maximum_size = 2 * (int) Math.pow(2, height) - 1;  
stArray = new int[maximum_size]; constructST(var, 0, s1 - 1, 0);  
}  
int getMidIndex(int f1, int l1)   
{  
return f1 + (l1 - f1) / 2;  
}  
int getSumUtil(int start, int end, int i_r, int j_r, int segment_index)  
{  
if (i_r <= start && j_r >= end)  
{  
return stArray[segment_index];  
}  
if (end < i_r || start > j_r)  
{  
return 0;  
}  
int mid_value = getMidIndex(start, end);  
return getSumUtil(start, mid_value, i_r, j_r, 2 * segment_index + 1) +  
    getSumUtil(mid_value + 1, end, i_r, j_r, 2 * segment_index + 2);  
}  
void updateValUtil(int start, int end, int j_u, int value, int segment_index)  
{  
if (j_u < start || j_u > end)  
{  
return;  
}
stArray[segment_index] = stArray[segment_index] + value;  
if (end != start)   
{  
int mid_value = getMidIndex(start, end);  
updateValUtil(start, mid_value, j_u, value, 2 * segment_index + 1);  
updateValUtil(mid_value + 1, end, j_u, value, 2 * segment_index + 2);  
}  
}   
void updateVal(int N[], int s1, int j_r, int new_value)  
{  
if (j_r < 0 || j_r > s1 - 1)   
{  
System.out.println("Invalid Input");  
return;  
} 
int different_value = new_value - N[j_r];  
stArray[j_r] = new_value; 
updateValUtil(0, s1 - 1, j_r, different_value, 0);  
}  
int getSum(int sum, int start, int end)  
{  
if (start < 0 || end > sum - 1 || start > end)   
{  
System.out.println("Invalid Input");  
return -1;  
}  
return getSumUtil(0, sum - 1, start, end, 0);  
}  
int constructST(int N[], int start, int end, int segment_index)  
{  
if (start == end)   
{  
stArray [segment_index ] = N[start];  
return N[start ] ;  
}   
int middle = getMidIndex ( start , end ) ;  
stArray [ segment_index ] = constructST ( N , start, middle, segment_index * 2 + 1) +  
    constructST ( N , middle + 1 , end , segment_index * 2 + 2 ) ;  
return stArray [ segment_index ] ;  
}  
public static void main(String argvs[])  
{  
int N[] = {22, 44, 77, 110, 2, 1};  
int size_array = N.length;
SegmentTree t = new SegmentTree(N, size_array);  
System.out.println ( " Sum of values within the specified range 1 to 4  = " + t . getSum ( size_array, 1, 4 ) ) ;  
 t. updateVal ( N , size_array , 3 , 11 ) ;  
System . out . println ( " Current sum of the values in the specified range = " + t.getSum ( size_array, 1, 4 ) ) ;  
}  
}  

Output :

Segment Tree in Java

Related Topics

How to Convert int to char in Java

To convert a higher data type to lower data type, we need to do typecasting. Casting is also required when we want to convert ASCII value into character. It is...

3 minutes read.

Diffie Hellman Algorithm in Java

In this section, you will be acknowledged about Diffie Hellman algorithm clearly step wise along with an example and also an example program. Diffie Hellman Algorithm One of the most significant algorithms...

3 minutes read.

Bifunction in java 8

A functional interface in Java is called BiFunction. It first appeared in Java 8. It can serve as the assigning target for a method reference or lambda expression. The java.util.function...

4 minutes read.

JDBC vs ODBC

Difference Between JDBC and ODBC ODBC: ODBC (Open Database Connectivity) is the accepted method for accessing databases among organisations and programmers. A database is linked to other programmes, such as word processors, spreadsheets,...

4 minutes read.

Grepcode Java util date

What is java.util.Date Class? The date and time in Java are provided through the java.util.Date class. If you imported java.util, it could be helpful. Use the Java.util.Date class to implement this class...

4 minutes read.

Difference between Constructor and Method in Java

What is Constructor? In Constructor, we will discuss constructors and also will discuss default constructors and finally, we will discuss overloading constructors. A constructor is a method that is used to...

13 minutes read.

Java this keyword

This Keyword in Java This keyword can be used in many different ways in Java. This is a reference variable in Java that points to the active object. In Java, the...

8 minutes read.

Java Integer compare() method

The compare() method of Integer class compares the two specified int values. Syntax public static int compare(int x, int y) Parameters The parameters ‘x’ and ‘y’ represent the first and second int values to...

2 minutes read.

Java InputStreamReader

What is InputStreamReader?An InputStreamReader is a converter between byte and character streams: It reads bytes and converts them to characters with the help of a charset. The charset it uses can...

4 minutes read.

Perfect Number in Java

The concept of a perfect number in Java will be defined in this chapter, along with creating Program code that determine whether a specific number is perfect or not. Additionally,...

4 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

Bubble Sort in Java

Bubble Sort in Java Bubble sort isalso known as sinking sort. It is one of the simplest sorting algorithms. In the bubble sort algorithm, the given array is traversed from left...

5 minutes read.

How to Reverse a String in Java

How to Reverse a String in Java There are a lot of ways to reverse a string in Java. One can use iteration, StringBuilder, StringBuffer to do the reverse of a...

6 minutes read.

Convert Char array to string in java

A collection of characters is referred to as a string. A character array differs from a string in that the string is canceled by the special character "\0." A string...

4 minutes read.

Deque in Java

Deque in java collections with Example Deque is short for “double-ended queue.” It is a linear collection that extends the Queue interface and supports insertion and deletion of the element at both the...

3 minutes read.

Scanner in Java

Static way of Programming: When a variable can’t change its value during run time is called a Static way of programming. In this programming a variable is directly assigned to a...

4 minutes read.

URLConnection Class

What is the URL? URL stands for Uniform Resource Locator, is used to specify addresses on the World Wide Web. A URL relates to the identification of any resource connected to the web. URL syntax: Protocol://hostname/other_information(files...

6 minutes read.

How to Calculate Week Number From Current Date in Java?

The WeekFields class's weekOfMonth() method is utilized to return the field for access the week of a month based on this WeekFields. If the first day of the month is a...

3 minutes read.

Java Break Keyword

Break: The word Break is a keyword or a statement in a java programming language.This Keyword break is used to stop the execution of the loop or switch statements etc.The loop...

3 minutes read.

How to take String Input in Java

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to...

5 minutes read.