Contents

Finding the Median (with.Java)

   Dec 21, 2023     1 min read

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

arrayresult
[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.