Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java and Algorithm problem. Please, show the stepss The balance index of an arra

ID: 3782846 • Letter: J

Question

Java and Algorithm problem. Please, show the stepss

The balance index of an array of integers is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. The formal definition is: The integer k is an balance index of a sequence of integers S[0]; S[1];...; S[n - 1] if and only if 0 lessthanorequalto k and sigma_i = 0^k - 1 S[i] = sigma_i = k + 1^n - 1 S[i]. Assume the sum of zero elements is equal to zero. For example, in a sequence S: S[0] = -5; S[1] =3; S[2] = 7; S[3] = -8; S[4] = -2; S[5]= 5; S[6] =2 3 is a balance index, because: S[0] + S[1] + S[2] = S[4] + S[5] + S[6] 6 is also a balance index, because: S[0] + S[1] + S[2] + S[3] + S[4] + S[5] = 0 And the sum of zero elements is zero. Note that the index 7 is not a balance index - because it is not a valid index of sequence S. Implement an efficient function in Java int ballndex(int S[], int n) that, given an array S, returns its balance index (any) or -1 if no balance index exists. What is the running time complexity of your function? Justify.

Explanation / Answer

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author Surya
*/
public class BalanceIndex {
  
    static int balIndex(int s[],int n)
    {
        int lsum,rsum,k=-1;//variable declaration
        int i,j;
        for(i=1;i<n-1;i++)//loop for finding balanced index
        {
            k=i;
            lsum=0;//variable to hold leftsum
            for(j=0;j<k;j++)
            {
                lsum=lsum+s[j];//calculating sum of elements left to index k
            }
            rsum=0;//variable to hold righttsum
            for(j=k+1;j<n;j++)
            {
                rsum=rsum+s[j];//calculating sum of elements right to index k
            }
            if(lsum==rsum)
            {
                return k;//returning balanced index
            }
        }
      
        k=-1;
        return k;//if not found such index then returning -1
    }
    public static void main(String argv[])
    {
        int s[]={-5,3,7,-8,-2,5,2};
        System.out.println(balIndex(s,7));
  
    }
  
}
//its complexity is O(n^2)...because it has two nested loops...

ouput:-

3

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote