Equilibrium index of an array is an index such that the sum of elements on whose left is equal to sum of elements on right in java . For example, in an array A:
A[0] = -7, A[1] = 1, A[2] = 5, A[3] = 2, A[4] = -4, A[5] = 3, A[6]=0
3 is an equilibrium index, because:
A[0] + A[1] + A[2] = A[4] + A[5] + A[6]
6 is also an equilibrium index, because sum of zero elements is zero, i.e., A[0] + A[1] + A[2] + A[3] + A[4] + A[5]=0
7 is not an equilibrium index, because it is not a valid index of array A.
OutPut:
A[0] = -7, A[1] = 1, A[2] = 5, A[3] = 2, A[4] = -4, A[5] = 3, A[6]=0
3 is an equilibrium index, because:
A[0] + A[1] + A[2] = A[4] + A[5] + A[6]
6 is also an equilibrium index, because sum of zero elements is zero, i.e., A[0] + A[1] + A[2] + A[3] + A[4] + A[5]=0
7 is not an equilibrium index, because it is not a valid index of array A.
public class EquilibriumJavaInHouse
{
public static void main(String[] args)
{
int arr[]={-5, 2, 4, 2, -4, 7, -4};
int i, j;
int leftsum, rightsum;
int count=0;
int arraylength=arr.length;
for (i = 0; i < arraylength; ++i)
{
leftsum = 0;
rightsum = 0;
for (j = 0; j < i; j++)
leftsum += arr[j];
for (j = i + 1; j < arraylength; j++)
rightsum += arr[j];
if (leftsum == rightsum)
{
System.out.println("Equilibirium found at"+i);
count++;
}
}
if(count==0)
System.out.println("No Equilibirium found ");
}
}
|
OutPut:
Equilibrium index of an array |
Post a Comment