2017-02-22 68 views
1
public class tryA { 

    public static void main(String[] args) { 
    int[] intArray= new int[41]; 
    System.out.println(intArray[intArray.length/2]); 

} 

如何爲我的整型數組intArray找到下四分位數(Q1)和第三四分位數(Q3)?假設數組的大小可能是一個變量。使用java查找整數數組中的第一四分位數和第三四分數

P.S:它用於查找數組的異常值。

+0

你想使用哪種方法?你需要告訴我們這一點。 –

+0

我試着用double LQ =(intArray [(median + 1)/ 2] + intArray [(median-1)/ 2])/2.0找到第一個四分位數;但似乎並不總是有效的 –

回答

0

我相信這是你正在尋找的,在代碼頂部更改quartile變量以在Q1,Q2,Q3和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; 
    } 
} 
相關問題