In this tutorial, you will learn how to find the median of numbers.
In this tutorial, you will learn how to find the median of numbers.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