Finding the median of all elements in an array.
Hints: Middle element
Here’s an example program in Java that finds the median of all elements in an array:
import java.util.Arrays; public class MedianFinder { public static double findMedian(int[] nums) { Arrays.sort(nums); // Sort the array in ascending order int length = nums.length; if (length % 2 == 0) { // If the length is even, average the middle two elements return (nums[length / 2 - 1] + nums[length / 2]) / 2.0; } else { // If the length is odd, return the middle element return nums[length / 2]; } } public static void main(String[] args) { int[] nums = {7, 2, 5, 1, 9, 4}; // Example array double median = findMedian(nums); System.out.println("Median: " + median); } }
This program defines a `MedianFinder` class with a `findMedian` method. The `findMedian` method takes an array of integers as input, sorts the array in ascending order using `Arrays.sort`, and then calculates the median based on the length of the array. The median is returned as a `double` value.
In the `main` method, we create an example array `nums` and call the `findMedian` method to find the median. Finally, we print the result to the console.
When you run this program, it will output:
Median: 4.5
which is the median of the elements in the array `{7, 2, 5, 1, 9, 4}`.
No comments yet! You be the first to comment.