简体   繁体   中英

Get the median from a 2D Array in Java

I'm all new to programming and I have started to learn Java 2 months ago. I have been assigned to do a small program, and a part of this program I have to get the median from a 2D array. The 2D array consists 3 subjects and a (N) number of students. I have to get the median for each subject, but I can not really understand how I'm going to sort the numbers from each subject.

Any help, tips or suggestion from were I should start is really appreciated.

Considering arr is your 2D array containing double values. Use the following code

Arrays.sort(arr, Comparator<double[]>() {
    public int compare(double a, double b) {
        return Double.compare(a[0], b[0]);
    }
});

Here Arrays and comparator are both available under java.util package. If you are using java 8, this can be done in a single line.

Arrays.sort(arr, (a,b) -> Double.compare(a[0], b[0]));

you can user java.util.arrays.sort() method.

import java.util.*;
public class MyClass {
public static void main(String args[]) {
    int N=10; // number of students
    double[][] array = new double[3][N];

    for (int i=0;i<3;i++)       
        for (int j=0;j<N;j++)
            array[i][j]= // students scores

    for (int i=0;i<3;i++) {
        double[] temp = new double[N];
        for (int j=0;j<N;j++)
            temp[j]=array[i][j];     // create an array for each subject

            Arrays.sort(temp);     // sort each array
            double median;
            if (temp.length % 2 == 0)   // find median for each case
                median = ((double)temp[temp.length/2] + (double)temp[temp.length/2 - 1])/2;
            else
            median = (double) temp[temp.length/2];
            System.out.println("Median of Subject " +(i+1)+" = " + median);
        }
    }
}

you can change data types as you want ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM