
How to get the median value in Java from the given list.

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("Enter 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);
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.