Sunday, November 24, 2019

Find middle index of array where both ends sum is equal

Java Program to Find middle index of array where both ends sum is equal.
Solution:- To get solution of the program we need to sum the element from both side. and compar them.
So i am going to start sum of elements from left side and sum of element from right side.

package example;

public class FindMiddleIndex {

 public static int findMiddleIndex(int[] numbers) throws Exception {

  int endIndex = numbers.length - 1;
  int startIndex = 0;
  int sumOfLeft = 0;
  int sumOfRight = 0;
  while (true) {
   if (sumOfLeft > sumOfRight) {
    sumOfRight += numbers[endIndex--];
   } else {
    sumOfLeft += numbers[startIndex++];
   }
   if (startIndex > endIndex) {
    if (sumOfLeft == sumOfRight) {
     break;
    } else {
     throw new Exception("Please pass valid array to match the requirement");
    }
   }
  }
  return endIndex;
 }

 public static void main(String a[]) {
  int[] num = { 1, 3, 6, 6, 3, 1 };
  try {
   System.out.println(
     "Sum of left element at index " + findMiddleIndex(num) + " is equal to sum of right element.");
  } catch (Exception ex) {
   System.out.println(ex.getMessage());
  }
 }
}
Output:

Sum of left element at index 2 is equal to sum of right element.

No comments:

Post a Comment