For working professionals
For fresh graduates
More
1. Introduction
6. PyTorch
9. AI Tutorial
10. Airflow Tutorial
11. Android Studio
12. Android Tutorial
13. Animation CSS
16. Apex Tutorial
17. App Tutorial
18. Appium Tutorial
21. Armstrong Number
22. ASP Full Form
23. AutoCAD Tutorial
27. Belady's Anomaly
30. Bipartite Graph
35. Button CSS
39. Cobol Tutorial
46. CSS Border
47. CSS Colors
48. CSS Flexbox
49. CSS Float
51. CSS Full Form
52. CSS Gradient
53. CSS Margin
54. CSS nth Child
55. CSS Syntax
56. CSS Tables
57. CSS Tricks
58. CSS Variables
61. Dart Tutorial
63. DCL
65. DES Algorithm
83. Dot Net Tutorial
86. ES6 Tutorial
91. Flutter Basics
92. Flutter Tutorial
95. Golang Tutorial
96. Graphql Tutorial
100. Hive Tutorial
103. Install Bootstrap
107. Install SASS
109. IPv 4 address
110. JCL Programming
111. JQ Tutorial
112. JSON Tutorial
113. JSP Tutorial
114. Junit Tutorial
115. Kadanes Algorithm
116. Kafka Tutorial
117. Knapsack Problem
118. Kth Smallest Element
119. Laravel Tutorial
122. Linear Gradient CSS
129. Memory Hierarchy
133. Mockito tutorial
134. Modem vs Router
135. Mulesoft Tutorial
136. Network Devices
138. Next JS Tutorial
139. Nginx Tutorial
141. Octal to Decimal
142. OLAP Operations
143. Opacity CSS
144. OSI Model
145. CSS Overflow
146. Padding in CSS
148. Perl scripting
149. Phases of Compiler
150. Placeholder CSS
153. Powershell Tutorial
158. Pyspark Tutorial
161. Quality of Service
162. R Language Tutorial
164. RabbitMQ Tutorial
165. Redis Tutorial
166. Redux in React
167. Regex Tutorial
170. Routing Protocols
171. Ruby On Rails
172. Ruby tutorial
173. Scala Tutorial
175. Shadow CSS
178. Snowflake Tutorial
179. Socket Programming
180. Solidity Tutorial
181. SonarQube in Java
182. Spark Tutorial
189. TCP 3 Way Handshake
190. TensorFlow Tutorial
191. Threaded Binary Tree
196. Types of Queue
197. TypeScript Tutorial
198. UDP Protocol
202. Verilog Tutorial
204. Void Pointer
205. Vue JS Tutorial
206. Weak Entity Set
207. What is Bandwidth?
208. What is Big Data
209. Checksum
211. What is Ethernet
214. What is ROM?
216. WPF Tutorial
217. Wireshark Tutorial
218. XML Tutorial
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.
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.