Created
May 31, 2018 12:52
-
-
Save viniru/c8562fd6db0df1d4f0ddedc5525cf34e to your computer and use it in GitHub Desktop.
segment tree to find sum in a particular interval of an array and to update the value at a particular index of the array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*package whatever //do not write package name here */ | |
import java.lang.Math; | |
public class segmentTree | |
{ | |
static int a[] = {1,2,3,4,5}; | |
static int tree[]; //segment tree that you will construct | |
public static void buildTree(int sb,int se) | |
{ | |
int numOfLeaves=a.length; | |
int height = (int)(Math.ceil(Math.log(numOfLeaves)/Math.log(2))); //not really used | |
int totalNodes = 2*numOfLeaves - 1; //total = n leaves(values in array a) + n-1 internal nodes in a"full" binary tree | |
tree = new int[totalNodes]; //above statement is always true . | |
buildTreeFinal(sb, se,0); //tree will have exactly "totalNodes" no. of nodes. | |
} | |
public static void getSum(int sb,int se) //s = segment b=beginning e = end | |
{ | |
if((sb<0 || sb > a.length-1)||(se<0 || se > a.length - 1) ||(se<sb)) | |
{ | |
System.out.println("Invalid input"); | |
System.exit(0); | |
} | |
System.out.println(getSumFinal(0,a.length-1,sb,se,0)); | |
} | |
public static int getSumFinal(int sb,int se,int b,int e,int ci) //ci = current index in the segment array | |
{ | |
if(sb >= b && se <= e) | |
return tree[ci]; | |
if(sb > e || se < b) | |
return 0; | |
int m=sb+(se-sb)/2; | |
return(getSumFinal(sb,m,b,e,2*ci+1)+getSumFinal(m+1,se,b,e,2*ci+2)); | |
} | |
public static void update(int val,int i) //update at index i. array a is untoched. | |
{ | |
updateFinal(val,i,0,a.length-1,0); | |
} | |
public static int updateFinal(int val,int i,int sb,int se,int ci) | |
{ | |
if(sb==se) | |
{ | |
int tmp=tree[ci]; | |
tree[ci]=val; | |
return tmp; | |
} | |
int x,y; | |
int m = sb+(se-sb)/2; | |
if(i <= m) | |
{ | |
y = updateFinal(val,i,sb,m,2*ci+1); | |
x = 2*ci+1; | |
} | |
else | |
{ | |
y = updateFinal(val,i,m+1,se,2*ci+2); | |
x = 2*ci+2; | |
} | |
tree[x] = tree[x] - y + val; | |
return y; | |
} | |
public static int buildTreeFinal(int sb,int se,int ci) | |
{ | |
if(sb==se) | |
{ | |
tree[ci]=a[sb]; | |
return a[sb]; | |
} | |
int mid=sb+(se-sb)/2; | |
tree[ci]=buildTreeFinal(sb,mid,2*ci+1)+buildTreeFinal(mid+1,se,2*ci+2); | |
return tree[ci]; | |
} | |
public static void main(String args[]) | |
{ | |
buildTree(0,a.length-1); //a is the original array | |
getSum(4,4); | |
update(5,0); | |
getSum(0,1); | |
update(5,1); | |
getSum(0,2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment