QuestionAsk Questions?

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

View Answers

February 16, 2012 at 12:29 PM

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); } }

Related Tutorials/Questions & Answers: