How to use Simple merging In Javascript
Merge the two given sorted arrays and sort them using the sort() method. If the length of the merged array is even then return the middle element as the median else if the length is even then return the average of the two middle elements.
Example: To demonstrate finding the Median of 2 sorted arrays of equal size using merging
function MedianOfSortedArrays(nums1, nums2) {
const mergedArray = nums1
.concat(nums2)
.sort((a, b) => a - b);
const n = mergedArray.length;
if (n % 2 === 0) {
return (mergedArray[n / 2 - 1] + mergedArray[n / 2]) / 2;
} else {
return mergedArray[Math.floor(n / 2)];
}
}
const nums1 = [1, 2, 3];
const nums2 = [4];
console.log(
"Median of 2 sorted array is :", MedianOfSortedArrays(nums1, nums2));
Output
Median of 2 sorted array is : 2.5
Time Complexity: O(m + n) , m and n are size of input array.
Space Complexity: O(1) , constant space.
Median of 2 Sorted Arrays of Equal Size using JavaScript
The median is the middle element of the array. If several elements are odd then the middle element is the median and if several elements are even then the average of the two middle values is the median after arranging the array in sorted order.
Below are the approaches to find the median of 2 sorted arrays of equal size using JavaScript:
Table of Content
- Using Simple merging
- Using Modified Binary Search