How to Get Quartiles in Java
For a brief overview of what quartiles are, you might read the Wikipedia page on this topic.
Basically, what it means is that if you were to break a list of numbers into four even parts, these would be the values that would separate them. But it gets a little complicated when your list doesn’t break into even chunks, etc. But I won’t get into the details of that here.
I threw together some code for getting the quartiles, which is below. I’ve also included some helper methods that I created to help with it. Also, note that I reused the Median method described here.
public static double[] Quartiles(ArrayList values) throws Exception { if (values.size() < 3) throw new Exception("This method is not designed to handle lists with fewer than 3 elements."); double median = Median(values); ArrayList lowerHalf = GetValuesLessThan(values, median, true); ArrayList upperHalf = GetValuesGreaterThan(values, median, true); return new double[] {Median(lowerHalf), median, Median(upperHalf)}; } public static ArrayList GetValuesGreaterThan(ArrayList values, double limit, boolean orEqualTo) { ArrayList modValues = new ArrayList(); for (double value : values) if (value > limit || (value == limit && orEqualTo)) modValues.add(value); return modValues; } public static ArrayList GetValuesLessThan(ArrayList values, double limit, boolean orEqualTo) { ArrayList modValues = new ArrayList(); for (double value : values) if (value < limit || (value == limit && orEqualTo)) modValues.add(value); return modValues; }
[...] Code Comments Tips and tutorials on various programming technologies, such as Python, Linux, Java, C#, and R. Please leave a comment! « How to Get Quartiles in Java [...]