w3resource
Java Programming Exercies

Java Exercises: Calculate the median of unsorted array of integers, find the median of it

Java Basic: Exercise-128 with Solution

Write a Java program to calculate the median of an given unsorted array of integers.
Example: {10,2,38,23,38,23,21}
Output: 23

Pictorial Presentation:

Java Basic Exercises: Calculate the median of unsorted array of integers, find the median of it.

Sample Solution:

Java Code:

import java.util.*; 
public class Main {
 public static void main(String[] args)
 {
    int[] nums = {10,2,38,23,38,23,21};
    System.out.println(Arrays.toString(nums));
    int n = nums.length;
		if (n < 1) {
			System.out.printf("False");
		}
		Queue<Integer> min = new PriorityQueue<Integer>(n);
		for (int num : nums) {
			min.add(num);
		}
		if ((n & 1) == 0) {
			n >>= 1;
			n -= 1;
		} else {
			n >>= 1;
		}
		int i = 0;
		while (i < n) {
			min.remove();
			i++;
		}
		System.out.print(min.remove()); 
    }
}

Sample Output:

[10, 2, 38, 23, 38, 23, 21]
23  

Flowchart:

Flowchart: Java exercises: Calculate the median of unsorted array of integers, find the median of it.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to get the Postorder traversal of its nodes' values of a given a binary tree.
Next: Java Data Types Exercises

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming