Home Tutorial Java Core Java Find Median

 
 

Share on Google+Share on Google+
Java Find Median
Posted on: September 22, 2012 at 12:00 AM
Advertisement
In this tutorial, you will learn how to find the median of numbers.

Java Find Median

In this tutorial, you will learn how to find the median of numbers.

There is no built in method to find the median of a list of numbers in the Java framework. But you can create your own method when you need to find the middle value in a set of numbers. The median is actually the middle value. If there is an even number of values, the median is the middle of these two numbers. Here we have created an example that stores 5 integers in an array randomly between the range of 30 to 50 and implement a method that computes the median from the set of numbers stored in an array.

Example:

import java.util.*;
class FindMedian{

public static int findMedian(int array[]) {
int length=array.length;
int[] sort = new int[length];
System.arraycopy(array, 0, sort, 0, sort.length);
Arrays.sort(sort);

if (length % 2 == 0) {
return (sort[(sort.length / 2) - 1] + sort[sort.length / 2]) / 2;
} else {
return sort[sort.length / 2];
}
}

public static void main(String[] args)
{
int min = 30;
int max = 50;
int[] ranNum = new int[5];
System.out.println("Numbers:");
for ( int i = 0; i < ranNum.length; i++) {
ranNum[i] = (int)(Math.random() * (max - min + 1) ) + min;
System.out.println(ranNum[i]);
}
int median=Find.findMedian(ranNum);
System.out.println("Median= "+median);
}
}

Output:

Numbers:
43
39
34
34
33
Median= 34

Advertisement

Related Tags for Java Find Median:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 22, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com