Median of two sorted arrays of same size
Find the median of two sorted arrays of equal length, taking values in order only up to the middle.
You are given two sorted arrays of integers, ab
Example 1
Output: 16.0
Explanation: in sorted order, the values are [1, 2, 12, 13, 15, 17, 26, 30, 38, 45]; the middle two are 15 and 17.
Example 2
Output: 2.5
The Idea
Imagine five friends standing in a line, from shortest to tallest. The median height is the height of the third friend, the one in the middle. With six friends there is no single middle person, so the median is the average of the third and the fourth.
Here the line always has 2n values, an even count, so the median is always the average of two middle values. In Example 1, n is 5 and there are 10 values. Lined up, they read 1, 2, 12, 13, 15, 17, 26, 30, 38, 45. The fifth and sixth are 15 and 17, and their average is 16.
The plain way to get there is to copy both arrays into one new sorted array of 10 values and read the middle. But look at what the median used: only the first six values of that line. The four after 17 played no part. So do we need to build the whole line at all?
We only need the values in sorted order, one at a time, up to the middle. Both arrays are sorted, so the smallest value not yet taken is always at the front of ab
The bottom row, labelled "taken in sorted order", shows the values in the order they are taken, with the step number under each one and the array it comes from, abababprevcurr
So the median needs only the first half of the sorted line, and only the last two values taken from it. Taking the smaller of two fronts, again and again, is the merge step of
Solution Approach
Turning this half-way merge into code means settling three things: how many values to take, what to remember while taking them, and what to do when one array runs out.
How many values to take
Why not merge both arrays fully and read the middle? That works, but it fills a new array of 2n values just to read two of them. Counting positions from 0, the two middle values of 2n values sit at positions n - 1 and n. Both are known once n + 1 values have been taken, so the loop can stop there. In Example 1, n is 5, so it takes 6 values, as in the picture.
Remembering the last two values
What do we keep while taking values? Only the last two. currprevcurrprevcurrprevcurr
When one array runs out
What if every value of one array is smaller than every value of the other? Take a = [5, 6]b = [1, 2]bbaabab
Can both arrays run out? No. Before each step at most n values have been taken. So if all n values of one array are gone, nothing has been taken from the other yet, and it still has all its values.
Java Solution
The method findMedian
- First, store the length of
ina . Start two indices at the front of each array:n fori anda forj . Setb andprev to 0.curr - Take n + 1 values with a
loop whose counter,for , runs from 0 to n.count - In each pass, copy
intocurr . Then takeprev ifa[i] is used up (b ) or ifj >= n still has values anda ; otherwise takea[i] <= b[j] . The taken value goes intob[j] , and its index moves one place along.curr - After the loop, return the average of
andprev . The sum is computed as acurr , a Java number type that keeps fractions and holds far bigger values thandouble .int
The mainbint
public class MedianOfTwoSortedArraysOfSameSize {
public static double findMedian(int[] a, int[] b) {
int n = a.length;
int i = 0; // next unused position in a
int j = 0; // next unused position in b
int prev = 0;
int curr = 0;
for (int count = 0; count <= n; count++) { // take n + 1 values in sorted order
prev = curr;
if (j >= n || (i < n && a[i] <= b[j])) {
curr = a[i++]; // b is used up, or a has the smaller front
} else {
curr = b[j++];
}
}
return (prev + (double) curr) / 2.0; // double: keeps the .5, cannot overflow
}
public static void main(String[] args) {
int[] a = {1, 12, 15, 26, 38};
int[] b = {2, 13, 17, 30, 45};
System.out.println(findMedian(a, b));
System.out.println(findMedian(new int[] {1, 2}, new int[] {3, 4}));
System.out.println(findMedian(new int[] {5, 6}, new int[] {1, 2}));
System.out.println(findMedian(new int[] {1}, new int[] {2}));
int max = Integer.MAX_VALUE;
System.out.println(findMedian(new int[] {max, max}, new int[] {max, max}));
}
}
Running it prints:
16.0
2.5
3.5
1.5
2.147483647E9
16.0 and 2.5 match Examples 1 and 2. The third line, 3.5, comes from a = [5, 6]b = [1, 2]ba
Look at the fourth line: 1.5 is the average of 1 and 2. If the method returned (prev + curr) / 2int
The last line, 2.147483647E9, is 2,147,483,647, the largest value an intintprevcurr(prev + curr) / 2.0doublecurrdouble
The original implementation,
Complexity
The method takes n + 1 values one by one and keeps only a few variables while doing it.
- Time: O(n), because the loop runs n + 1 times, one more than the length of each array, and each pass does one comparison and moves one index.
- Space: O(1). No merged array is built: the method keeps only
,i ,j ,prev andcurr .count
Because both arrays are sorted, the median can also be found by binary search, which halves the range of candidates at every step. That takes O(log n) steps and also works for arrays of different sizes: see