-2

I have to find the sum of the elements before and after the median, that are close as possible. For example: Input: {4,5,99,-1,5,6} Output: 3 (element with index 3) //we start counting from 1

public int median(int[] array) {
    int index = 0;
    int minSum;
    int sum = 0;
    int leftSum = 0;
    int rightSum = 0;
    int[] subtraction = new int[array.length];

    for (int i = 1; i < array.length; i++) {
        sum = array[i] + sum;
    }
    rightSum = sum;
    subtraction[0] = rightSum - leftSum;

    for (int i = 1; i < array.length; i++) {

        leftSum = leftSum + array[i - 1];

        rightSum = sum - array[i];
        if (leftSum > rightSum) {
            subtraction[i] = leftSum - rightSum;
        } else {
            subtraction[i] = rightSum - leftSum;
        }

    }

    minSum = subtraction[0];
    for (int i = 1; i < subtraction.length; i++) {
        if (subtraction[i] < minSum) {
            minSum = subtraction[i];
            index = i;
        }
    }

    return index + 1;
}

I know i don't have to look for the minimum value but i can't find another way.My question is how to i find the closest numbers?

Blake Yarbrough
  • 2,286
  • 1
  • 20
  • 36
P.Peev
  • 13
  • 1
  • 3

1 Answers1

0

OUTPUT:

median is: 5 at index: 3

public class Hello {

      static int[] integerArray = {4,5,99,-1,5,6};

      public static void main(String[] args){
          List<Integer> sortedArray = new ArrayList<Integer>();

          //fill up a Collection (ArrayList<Integer>) with your array values
          for(int integer : integerArray){
              sortedArray.add(integer);
          }

          //sort the collection
          Collections.sort(sortedArray);

          //get the index of the median (middle item of a sorted list)
          int index = sortedArray.size() / 2;

          //print the median and it's index
          System.out.println("median is: " + sortedArray.get(index) + " at index: " + index);
      }
}
Blake Yarbrough
  • 2,286
  • 1
  • 20
  • 36
  • I dont have to sort it . The sum ot the left and the sum on the right have to be as close as possible. OUTPUT: 4,5,99,-1,5,6 the meddian is index 3 element 99 (left sum 9)(right sum 10) – P.Peev Aug 24 '15 at 14:52
  • @P.Peev Actually median implies a sorted set of data, see https://en.wikipedia.org/wiki/Median. If you are not looking for the median of the set, then consider rewording your Question. – Blake Yarbrough Aug 24 '15 at 15:42