Median of Two Sorted Arrays of Different Sizes using JavaScript
Last Updated :
16 May, 2024
Given two arrays, our goal is to find the median of two sorted arrays of different sizes by merging both of them. The median is the middle value of the array after dividing it into two halves.
Example:
Input: Arr1: [1,4,5], Arr2: [2,8,7,3]
Output: Median = 4
Explanation: The merged and sorted array is: ar3[] = [1,2,3,4,5,7,8]
The median is 4
Using Binary Search
In this approach, we will be performing binary search on the shorter array so that we can partition it in such a way that the newly combined left half of both the arrays will have elements less than the combined right half. Adjust the partition point until the condition for median gets satisfied. If the combined length of the new array is odd, return the maximum element of the left partition. If it's even, return the average of the maximum element of the left partition and the minimum element of the right partition.
Example: The below example shows how to find Median of two sorted arrays of different sizes using Binary Search on the Smaller Array.
JavaScript
function find_Median_Fun(no1, no2) {
// Checks whether no1 is the smaller array
if (no1.length > no2.length) {
return find_Median_Fun(no2, no1);
}
const m = no1.length;
const n = no2.length;
let low = 0, high = m;
// Perform binary search
while (low <= high) {
// Calculate partition points
const partitionX = Math.floor((low + high) / 2);
const partitionY = Math.floor((m + n + 1) / 2) - partitionX;
// Find elements to the left and
// right of the partition for both arrays
const maxX = partitionX === 0 ?
Number.NEGATIVE_INFINITY :
no1[partitionX - 1];
const maxY = partitionY === 0 ?
Number.NEGATIVE_INFINITY :
no2[partitionY - 1];
const minX = partitionX === m ?
Number.POSITIVE_INFINITY :
no1[partitionX];
const minY = partitionY === n ?
Number.POSITIVE_INFINITY :
no2[partitionY];
// Check if partitions are correct
if (maxX <= minY && maxY <= minX) {
// If the combined length of the arrays is even
// return the average of the middle elements
if ((m + n) % 2 === 0) {
return (Math.max(maxX, maxY) +
Math.min(minX, minY)) / 2;
} else {
// If the combined length of the arrays is odd,
// return the maximum of the middle elements
return Math.max(maxX, maxY);
}
} else if (maxX > minY) {
// If partitionX is too big,
// move partitionX to the left
high = partitionX - 1;
} else {
// If partitionX is too small,
// move partitionX to the right
low = partitionX + 1;
}
}
}
const no1 = [1, 3];
const no2 = [2];
console.log(find_Median_Fun(no1, no2));
Time Complexity: O(log(min(m, n))), where m and n are the lengths of the two input arrays.
Space Complexity: O(1)
Using Two-Pointers Approach
The function find_Median_fun finds the median of two sorted arrays by iterating through them simultaneously with two pointers, selecting elements in ascending order until reaching the middle point of the combined arrays. It determines the median based on whether the total length is even or odd and returns the result accordingly.
Example: The example below shows how to find Median of two sorted arrays of different sizes using JavaScript Using Two-Pointers.
JavaScript
function find_Median_fun(nums1, nums2) {
const totalLength = nums1.length + nums2.length;
const ifEven = totalLength % 2 === 0;
const halfLength = Math.floor(totalLength / 2);
// 2 pointers
let i = 0, j = 0;
let count = 0;
let median = 0, prevMedian = 0;
while (count <= halfLength) {
prevMedian = median;
if (i < nums1.length &&
(j >= nums2.length || nums1[i] < nums2[j])) {
median = nums1[i];
i++;
} else {
median = nums2[j];
j++;
}
count++;
}
// If length is even
if (ifEven) {
return (prevMedian + median) / 2;
} else {
return median;
}
}
const nums1 = [1, 3];
const nums2 = [2];
console.log("Median:",
find_Median_fun(nums1, nums2));
Time Complexity: O(m + n), where m and n are the lengths of the two input arrays.
Space Complexity: O(1)
Similar Reads
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
3 min read
JavaScript- Merge two Sorted Arrays These are the following ways to merge two sorted arrays: 1. Using Two Pointers (Efficient For Large Arrays)This approach involves using two pointers, one for each array, and comparing their elements as you iterate through them. This method works efficiently in O(n + m) time, where n and m are the le
3 min read
Merge K Sorted Array using JavaScript We are given K sorted arrays and our task is to merge them into a single sorted array in JavaScript.Example:Input: arrays = [[2, 4, 5], [1, 3, 8], [0, 7, 9]];Output: [0, 1, 2, 3, 4, 5, 7, 8]These are the following approaches:Table of ContentNaive ApproachDivide and Conquer ApproachMin-Heap ApproachN
5 min read
Find Kth Element of Two Sorted Arrays in JavaScript Given two sorted arrays, our task is to find the Kth element in the combined array made by merging the two input arrays in JavaScript.Example:Input: Arr1: [1, 2, 5] , Arr2:[2, 4, 6, 8], K = 4Output: Kth element is 4.Explanation:The final Array would be: [1, 2, 2, 4, 5, 6, 8]The 4th element of this a
3 min read
JavaScript - Sort JS Array with Different Data Types To sort a JS array having different data types we can sort the elements by converting them to similar types, using type-based sorting, or by using external libraries like lodash and underscore.js. 1. Sorting with String ConversionConvert the elements to strings using String() constructor, and then u
2 min read
Swapping two array elements in a single line using JavaScript In JavaScript, there exist many ways by which one can swap two array elements. In this article, we will discuss a way in which one can swap two array elements in JavaScript in a single line. The input and output would be as follows. Input: arr = { 10, 20, 40, 30 }Output: arr = { 10, 20, 30, 40 } //
3 min read
Javascript Program to Print uncommon elements from two sorted arrays Given two sorted arrays of distinct elements, we need to print those elements from both arrays that are not common. The output should be printed in sorted order. Examples :Input : arr1[] = {10, 20, 30} arr2[] = {20, 25, 30, 40, 50}Output : 10 25 40 50We do not print 20 and 30 as theseelements are pr
2 min read
Javascript Program to Find median in row wise sorted matrix We are given a row-wise sorted matrix of size r*c, we need to find the median of the matrix given. It is assumed that r*c is always odd.Examples: Input : 1 3 5 2 6 9 3 6 9Output : Median is 5If we put all the values in a sorted array A[] = 1 2 3 3 5 6 6 9 9)Input: 1 3 4 2 5 6 7 8 9Output: Median is
4 min read
Sorting Array of Number by Increasing Frequency using JavaScript To sort an array of given numbers based on the frequency of occurrence of each number first sort the array such that the elements repeated for the least number of times appear first followed by the elements with increasing frequency. Example: Input:array = [3, 3, 1, 1, 1, 8, 3, 6, 8, 8] Output:[6, 1
3 min read
How to Swap Two Array of Objects Values using JavaScript ? Swapping values between two arrays of objects is a common operation in JavaScript, there are multiple methods to swap values between arrays of objects efficiently. Swapping values between arrays can be useful in scenarios like reordering data, shuffling items, or performing certain algorithms. These
6 min read