Search code examples
javaarraylistmedian

Wrong Median Answer


Problem: I'm having an issue with counting the median value of my arrayList

Background: So my ArrayList gets randomly generated values and i have to calculate median of it; i believe my median formula is fine yet i'm getting wrong median answers for 3 values in an ArrayList.

for like three values, it's giving the wrong median. E.G: when the array list has the values: 193.5, 200.5, 239.8 then the program is simply taking the average of first two values and giving the answer instead of going for 200.5

public double getMedianB(){
    Collections.sort(myDataB);
    double middle = myDataB.size()/2;
    if (myDataB.size()%2 == 1) {
       middle = (myDataB.get(myDataB.size()/2) + myDataB.get(myDataB.size()/2 - 1))/2;
    } else {
        middle = myDataB.get(myDataB.size() / 2);
    }
    System.out.println("median:" + middle);
  return middle;
}

Solution

  • Median is calculated by

    1. Arrange list in ascending order
    2. If number of items in list are odd, then the middle number is the median
    3. If number of items are even, then add the middle two numbers and divide it by two, this result will be the median

    In your code you have conditions for even and odd switched, so correct one would be as below

    if (myDataB.size()%2 == 0) {
       middle = (myDataB.get(myDataB.size()/2) + myDataB.get(myDataB.size()/2 + 1))/2;
    } else {
        middle = myDataB.get(myDataB.size() / 2);
    }