Java - Calculate Median
Here is the Java Source to calculate median for a given set of numbers.
Source Code
import java.io.*;
class CalcMedian {
public static void main(String[] args) {
String inpstring = "";
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
try
{
System.out.print("Enter a Number Elements to calculate Median:");
inpstring = reader.readLine();
long max = Long.parseLong(inpstring);
long[] arrElements = new long[100];
for (int i = 0; i < max; i++)
{
System.out.print("Enter [" + (i + 1) + "] Element: ");
inpstring = reader.readLine();
arrElements[i] = Long.parseLong(inpstring);
}
for(int i = 1; i < max; i++)
{
for(int j = 0; j < max - i; j++)
{
if(arrElements[j] > arrElements[j + 1])
{
long temp = arrElements[j];
arrElements[j] = arrElements[j + 1];
arrElements[j + 1] = temp;
}
}
}
if ((max % 2) == 1)
{
// for odd count
int index = (int) max / 2;
System.out.println("Median: " + arrElements[index]);
}
else
{
// if there 10 elements (index 0-9),
// average of (10/2 = 5th) and (10/2-1 = 4th) element
int index1 = (int) max / 2;
int index2 = index1 - 1;
double value = (arrElements[index1] + arrElements[index2]) / 2.0;
System.out.println("Median: " + value);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Output
D:\Program Files\Java\jdk1.6.0_23\bin>java CalcMedian
Enter a Number Elements to calculate Median:5
Enter [1] Element: 10
Enter [2] Element: 5
Enter [3] Element: 30
Enter [4] Element: 2
Enter [5] Element: 30
Median: 10
|