Median Of Numbers In Java Example
Chapter:
Math Class
Last Updated:
05-05-2016 18:56:05 UTC
Program:
/* ............... START ............... */
import java.util.*;
public class JavaMedianExample {
public static void main(String[] args) {
int scores[] = new int[] { 50,40,34,56,84,23,45,50,30,40 };
Arrays.sort(scores);
System.out.print("Sorted Scores: ");
for (int x : scores) {
System.out.print(x + " ");
}
System.out.println("");
// Calculate median (middle number)
double median = 0;
double pos1 = Math.floor((scores.length - 1.0) / 2.0);
double pos2 = Math.ceil((scores.length - 1.0) / 2.0);
if (pos1 == pos2) {
median = scores[(int) pos1];
} else {
median = (scores[(int) pos1] + scores[(int) pos2]) / 2.0;
}
System.out.println("Median: " + median);
}
}
/* ............... END ............... */
Output
Sorted Scores: 23 30 34 40 40 45 50 50 56 84
Median: 42.5
Tags
Median Of Numbers, Java, Math