Tutorial Playlist
Computer science or mathematical applications often require finding the median of two sorted arrays. The median is the middle value when the two arrays are merged and sorted. This median can be found using a variety of algorithms and helps reveal the data's primary tendency.
This guide describes multiple efficient ways to calculate the median of two sorted arrays of varying and equal sizes. We will include programmed examples, outputs, and brief explanations to help you grasp each procedure. With a proper understanding, you will be able to successfully implement these techniques in your programming tasks.
The median of two sorted arrays is a pivotal value, often used in statistics, data analysis, and algorithm optimization. Efficiently computing this value is crucial for improving performance in various applications. In this article, we will explore different techniques to calculate the median, including merging arrays, binary search, priority queues, and simulated stacks. By the end of this tutorial, you’ll be highly skilled and able to use this versatile and useful tool in a variety of applications. So, let’s get started!
Concept:
To find the median of two sorted arrays with different sizes, we can merge the arrays virtually using a two-pointer approach without merging them physically. We maintain two pointers, one for each array, and move them accordingly to keep track of the middle elements.
Example:
Output:
Explanation:
- In this example, the code defines a function named `find_median`, which takes two sorted arrays `arr1` and `arr2` as input parameters.
- The function merges the two arrays into a new list called ‘merged', maintaining the sorted order of elements.
- It uses two pointers `i` and `j` to traverse through both arrays `arr1` and `arr2`.
- The merged array contains all elements from `arr1` and `arr2` in sorted order.
- The median is then calculated based on the merged array's length, `n`.
- If the total number of elements in the merged array is even, the median is the average of the two middle elements.
- If the total number of elements is odd, the median is the middle element itself.
- The `find_median` function returns the calculated median, which is printed in the example using the given arrays `[2, 4, 6, 8, 10]` and `[1, 3, 5]`.
- The output will be: `Median: 4`.
Concept:
To determine the median using binary search, the arrays must be partitioned such that the elements on the left are smaller than the elements on the right. The median is then the average of the largest element on the left and the smallest element on the right.
Example:
Output:
Explanation:
Concept:
We can use a priority queue data structure to merge the two arrays efficiently while maintaining the correct order of elements.
Example:
Output:
Explanation:
In this example, the two sorted arrays are [1, 3, 5, 7] and [2, 4, 6]. We use a priority queue to merge the arrays, and the merged queue becomes [1, 2, 3, 4, 5, 6, 7]. The median is 4.0.
Concept:
The simulated stack performs operations similar to a merge operation in merge sort, helping us find the median effectively.
Example:
def findMedianSortedArrays(arr1, arr2):
m, n = len(arr1), len(arr2)
total = m + n
stack = []
ptr1, ptr2 = 0, 0
while len(stack) < total // 2 + 1:
if ptr1 < m and (ptr2 >= n or arr1[ptr1] < arr2[ptr2]):
stack.append(arr1[ptr1])
ptr1 += 1
else:
stack.append(arr2[ptr2])
ptr2 += 1
if total % 2 == 0:
return (stack[-1] + stack[-2]) / 2.0
else:
return float(stack[-1])
# Example
arr1 = [1, 3, 8, 9, 15]
arr2 = [7, 11, 18, 19, 21, 25]
median = findMedianSortedArrays(arr1, arr2)
print(f"Median: {median}")
Output:
Median: 9.0
The median of these two sorted arrays is 9.0. This is the average of the two middle elements from the merged array: [1, 3, 7, 8, 9, 11, 15, 18, 19, 21], which are 8 and 9.
Explanation:
Concept:
When both input arrays have the same size, finding the median is relatively straightforward. We can merge the arrays and calculate the median based on the merged result.
Example (using pseudo-code):
Suppose we have two sorted arrays, `arr1` and `arr2`, each of size `n`. We will virtually merge the arrays to find the median.
Example (using values):
Suppose we have two sorted arrays [1, 3, 5] and [2, 4, 6], both with the same size of 3.
In the above example, the function findMedian efficiently finds the median of the merged array [1, 2, 3, 4, 5, 6], which is 3.5.
Please note that this is a pseudo-code representation of the concept, and you can use similar merging and median calculation steps in any programming language of your choice to find the median of two sorted arrays of the same size.
Concept:
We can implement various algorithms to find the median of two sorted arrays in C. One common approach is to use a two-pointer technique to virtually merge the arrays.
Example in C:
Output:
Explanation:
Concept:
Divide and conquer is a widely used technique to find the median of two sorted arrays efficiently. We partition both arrays and compare the elements around the median to arrive at the answer.
Example:
Output:
Explanation:
Concept:
The divide and conquer algorithm divides two sorted arrays into halves, with smaller elements in the left half. Finding the partition points determines the median of the combined arrays. This approach lowers the search space in logarithmic time (O(log(min(m, n))) and processes even and odd-sized arrays.
Example:
```java
public class MedianOfTwoSortedArrays {
public static double findMedian(int[] nums1, int[] nums2) {
int m = nums1.length;
int n = nums2.length;
if (m > n) {
// Swap the arrays and sizes to ensure nums1 is smaller.
int[] tempArr = nums1;
nums1 = nums2;
nums2 = tempArr;
int tempSize = m;
m = n;
n = tempSize;
}
int imin = 0, imax = m, halfLen = (m + n + 1) / 2;
while (imin <= imax) {
int i = (imin + imax) / 2;
int j = halfLen - i;
if (i < m && nums2[j - 1] > nums1[i]) {
// i is too small, increase it
imin = i + 1;
} else if (i > 0 && nums1[i - 1] > nums2[j]) {
// i is too big, decrease it
imax = i - 1;
} else {
// i is perfect, get the median
int maxLeft;
if (i == 0) {
maxLeft = nums2[j - 1];
} else if (j == 0) {
maxLeft = nums1[i - 1];
} else {
maxLeft = Math.max(nums1[i - 1], nums2[j - 1]);
}
if ((m + n) % 2 == 1) {
return maxLeft;
}
int minRight;
if (i == m) {
minRight = nums2[j];
} else if (j == n) {
minRight = nums1[i];
} else {
minRight = Math.min(nums1[i], nums2[j]);
}
return (maxLeft + minRight) / 2.0;
}
}
return 0.0;
}
public static void main(String[] args) {
int[] arr1 = {1, 3, 5, 7};
int[] arr2 = {2, 4, 6, 8, 10};
double median = findMedian(arr1, arr2);
System.out.println("Median: " + median);
}
}
```
Output:
Explanation:
In this example, we have two sorted arrays, `arr1 = {1, 3, 5, 7}` and `arr2 = {2, 4, 6, 8, 10}`.
The `findMedian` function uses the divide and conquer approach to find the median. After evaluating the arrays, the median is calculated as 5.5.
The time complexity of this algorithm is O(log(min(m, n))), where m and n are the sizes of the two input arrays. The example demonstrates how the divide and conquer technique efficiently finds the median in logarithmic time complexity, even for larger arrays.
The median of two sorted arrays is a fundamental concept with widespread applications. By understanding the efficient techniques we covered—merging arrays, binary search, priority queues, and simulated stacks—you can confidently find the median, regardless of the array sizes. These techniques optimize algorithms and can be applied to various real-world scenarios.
Q: When computing the median of two sorted arrays, what happens if one input array is empty?
If one array is empty, the median is the middle element of the non-empty array's odd length. The median of an even-length array is the average of the two middle components. Correct median computation requires empty array handling.
Q: Do I need to sort the array to find the median?
Yes, you must sort the array to find the median. Determine if the array has even or odd elements. Return the array's midpoint if odd. The median is the average of the two middle numbers in all other circumstances.
Q: Which sorted array has the best performance?
Quicksort is the most efficient sorting algorithm for common applications, especially when input array properties are unknown. It beats insertion sort for large lists.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...