int size = values.size();
if (size == 0) return null;
// sort the list
Object sampleValue = values.get(0);
OrdinalType ordinalType = getOrdinalType(sampleValue);
if (sampleValue instanceof Comparable)
Collections.sort(values);
else {
Collections.sort(values, ordinalType.getComparator());
}
// median is calculated as the middle item in the list for lists with an odd number of items
// and as an average of two middle items for lists with an even number of rows
if (size % 2 == 1) {
return values.get(size / 2);
} else {
int middleIndex = size / 2;
Object value1 = values.get(middleIndex - 1);
Object value2 = values.get(middleIndex);
Object sum = ordinalType.add(value1, value2);
return ordinalType.divide(sum, 2);
}
}
};
}