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;
}
Median is calculated by
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);
}