Finding the Median (with.Java)
This is the āFind the medianā problem.
Weāre going to learn by solving coding test problems, reflecting on the problems weāve solved, and exploring other ways to solve them.
Letās start with the problem
The problem
The median is the value that is most centered when a given set of values is ordered by size.
For example, the median of 1, 2, 7, 10, and 11 is 7.
Complete the solution function so that it returns the median when given an array of integers as a parameter.
Example input and output
array | result |
---|---|
[1, 2, 7, 10, 11] | 7 |
[9, -1, 0] | 0 |
My solution to the ### problem
import java.util.Arrays;
class Solution {
public int solution(int[] array) {
int answer = 0;
Arrays.sort(array);
answer = array[array.length / 2];
return answer;
}
}
Solution
import java.util.Arrays;: imports Javaās Arrays class to sort an array.
public int solution(int[] array) : Declares a function solution, it takes an integer array array as input parameter, this function returns an integer value.
int answer = 0;: Declares an integer variable, answer, to store the resulting value and initializes it to 0.
Arrays.sort(array);: Sorts the input array array. This code sorts the array in ascending order, so the smallest value in the array will be in array[0] and the largest value will be in array[array.length - 1].
answer = array[array.length / 2];: Store the element in the middle of the sorted array, the median, in the answer variable. Dividing the length of the array by 2 gives us the index of the median. This code returns exactly the median when the length of the array is odd, and the smaller of the two values in the middle when it is even.
return answer;: Returns the answer variable, including the middle value, as the return value of the function.