![]() |
VOOZH | about |
Given two sorted arrays, a[] and b[], find the median of these sorted arrays. Assume that the two sorted arrays are merged and then median is selected from the combined array.
This is an extension of Median of two sorted arrays of equal size problem. Here we handle arrays of unequal size also.
Examples:
Input: a[] = [-5, 3, 6, 12, 15], b[] = [-12, -10, -6, -3, 4, 10]
Output: 3
Explanation: The merged array is [-12, -10, -6, -5 , -3, 3, 4, 6, 10, 12, 15]. So the median of the merged array is 3.Input: a[] = [1], b[] = [2, 4, 5, 6, 7]
Output: 4.5
Explanation: The merged array is [1, 2, 4, 5, 6, 7]. The total number of elements are even, so there are two middle elements. Take the average between the two: (4 + 5) / 2 = 4.5
Table of Content
The idea is to combines both sorted arrays into a new array and then sorts it. Once sorted, it finds the median by checking the total length. If the size is odd, it returns the middle element; if even, it returns the average of the two middle elements. This method is straightforward but not optimal in terms of time and space complexity.
Illustration:
a[] = [ -5, 3, 6, 12, 15 ], b[] = [ -12, -10, -6, -3, 4, 10 ]
- After concatenating them in a third array: c[] = [ -5, 3, 6, 12, 15, -12, -10, -6, -3, 4, 10]
- Sort c[] = [ -12, -10, -6, -5, -3, 3, 4, 6, 10, 12, 15 ]
- As the length of c[] is odd, so the median is the middle element = 3
3
The idea is to simulate the merging process of two sorted arrays without actually creating a new one. By iterating through both arrays together until reaching the middle index, the algorithm keeps track of the last two selected elements.
These are then used to compute the median: if the total number of elements is odd, the middle element is returned; if even, the average of the two middle elements is returned. This ensures correct handling for both even and odd combined lengths.
3
Prerequisite: Median of two sorted arrays of same size
The approach is similar to the Binary Search approach of Median of two sorted arrays of same size with the only difference that here we apply binary search on the smaller array instead of a[].
Why do we apply Binary Search on the smaller array?
Applying Binary Search on the smaller array helps us in two ways:
To avoid handling such cases, we can simply binary search on the smaller array.
3