Reputation:
public class tryA {
public static void main(String[] args) {
int[] intArray= new int[41];
System.out.println(intArray[intArray.length/2]);
}
How to find the Lower Quartile (Q1) and Third Quartile (Q3) for my integer Array intArray? Providing that the size of array might be a variables.
P.S: It is used to find the outlier of the array.
Upvotes: 3
Views: 8696
Reputation: 31
My solution is plug and play! You just give an array (val) of double numbers and it gives you back an array with 3 doubles Q1 in position 0, Q2 in position 1 and Q3 in position 2.
public double[] Quartiles(double[] val) {
double ans[] = new double[3];
for (int quartileType = 1; quartileType < 4; quartileType++) {
float length = val.length + 1;
double quartile;
float newArraySize = (length * ((float) (quartileType) * 25 / 100)) - 1;
Arrays.sort(val);
if (newArraySize % 1 == 0) {
quartile = val[(int) (newArraySize)];
} else {
int newArraySize1 = (int) (newArraySize);
quartile = (val[newArraySize1] + val[newArraySize1 + 1]) / 2;
}
ans[quartileType - 1] = quartile;
}
return ans;
}
Upvotes: 1
Reputation: 174
You can derive this from the percentiles. For calculating percentiles in Java, there is a nice solution: Calculate percentile from a long array?
Upvotes: 0
Reputation: 954
I believe this is what you are looking for, change the quartile
variable at the top of the code to change between Q1, Q2, Q3 and Q4.
import java.util.Arrays;
public class ArrayTest
{
public static void main(String[] args)
{
//Specify quartile here (1, 2, 3 or 4 for 25%, 50%, 75% or 100% respectively).
int quartile = 1;
//Specify initial array size.
int initArraySize = 41;
//Create the initial array, populate it and print its contents.
int[] initArray = new int[initArraySize];
System.out.println("initArray.length: " + initArray.length);
for (int i=0; i<initArray.length; i++)
{
initArray[i] = i;
System.out.println("initArray[" + i + "]: " + initArray[i]);
}
System.out.println("----------");
//Check if the quartile specified is valid (1, 2, 3 or 4).
if (quartile >= 1 && quartile <= 4)
{
//Call the method to get the new array based on the quartile specified.
int[] newArray = getNewArray(initArray, quartile);
//Print the contents of the new array.
System.out.println("newArray.length: " + newArray.length);
for (int i=0; i<newArray.length; i++)
{
System.out.println("newArray[" + i + "]: " + newArray[i]);
}
}
else
{
System.out.println("Quartile specified not valid.");
}
}
public static int[] getNewArray(int[] array, float quartileType)
{
//Calculate the size of the new array based on the quartile specified.
int newArraySize = (int)((array.length)*(quartileType*25/100));
//Copy only the number of rows that will fit the new array.
int[] newArray = Arrays.copyOf(array, newArraySize);
return newArray;
}
}
Upvotes: 0