2016-02-20 34 views
1

現在參加一個編程課程,我很困惑到最大。我們基本上需要聲明一箇中值方法,它將查找數組對象中包含的值的中值,我不知道如何在這種情況下操作它。此外,我不知道如何分離數組的各個部分或如何獲得數組的特定「中間塊」,有點像合併排序,但是我們甚至都沒有接近過。如何查找數組對象的中位數?

我一直在努力解決這個問題,整個星期。這是我的所有代碼。 任何提示或提示將是驚人的。謝謝

class ArrayIns { 
    private long[] a; 
    private int nElems; // number of data items 

    public ArrayIns(int max) { // constructor 
     a = new long[max]; // create array 
     nElems = 0; // no items yet 
    } 

    public void insert(long value) { 
     a[nElems] = value; 
     nElems++; 
    } 

    public void display() { 
     for(int j=0; j<nElems; j++) 
      System.out.print(a[j] + " "); 
     System.out.println(""); 
    } 

    public void insertionSort() { 
     int in, out; 

     for(out=1; out<nElems; out++) {   // out is dividing the line 
      long temp = a[out];     // remove marked item 
      in = out;       // start shifts at our 
      while(in>0 && a[in-1] >= temp) { // until one is smaller, 
       a[in] = a[in-1];  // shift item to right 
       --in;    // go left one position 
      } 
      a[in] = temp;  // insert marked item 
     } // end of for statement 
    } // end of insertion sort 
} // end of ArrayIns 

class InsertSortApp { 
    public static void main(String[] args) { 
     int maxSize = 100; 
     ArrayIns arr; 
     arr = new ArrayIns(maxSize); 

     arr.insert(77); // insert 10 items 
     arr.insert(99); // 10 is also even :) 
     arr.insert(44); 
     arr.insert(55); 
     arr.insert(22); 
     arr.insert(88); 
     arr.insert(11); 
     arr.insert(00); 
     arr.insert(66); 
     arr.insert(33); 

     arr.display(); 

     arr.insertionSort(); 

     arr.display(); 
    } // end of main() 
} // end of InsertSortApp class 

回答

-1

添加以下方法來ArrayIns

public long median() { 
    if (nElems % 2 == 0) { 
     int index1 = nElems/2-1; 
     return (a[index1]+a[index1+1])/2; 
    } 
    return a[nElems/2]; 
} 

而且從main()的調用後您排序:

long median = arr.median(); 
1

首先,你測試你的排序算法,看看它的工作原理?它是否正確排序陣列?

如果排序算法正常工作,那麼獲取中位數很簡單。首先,確定它是否有奇數或偶數的元素。如果它具有奇數個元素,則中位數是元素的長度/ 2。如果它具有偶數個元素,則中值是元素的平均長度/ 2 - 1和長度/ 2。