Search code examples
javaarrayssortingmedian

How to find the median of an array object?


Taking a programming class right now and I'm confused to the max. We basically need to declare a median method that will find the median of the values contained within the array object, and I have no clue how to manipulate that in this scenario. Furthermore, I have no knowledge of how to seperate the pieces of the array or how to get the specific "middle chunks" of the array, sort of like in merge sorting, however we haven't even gotten close to that.

I've been struggling with this problem all week. Here's all of my code. Any tips or hints would be amazing. Thank you

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

Solution

  • Add the following method to ArrayIns

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

    And from main() call after you sort:

    long median = arr.median();