Find Median of Sorted Arrays

JavaScript

Concepts of Median

The median is a measure of central tendency in statistics that represents the middle value of a dataset when it is ordered from smallest to largest. It divides the dataset into two equal halves: one half contains values greater than or equal to the median, and the other half contains values less than or equal to the median.

E.g.: When the dataset has an odd number of observations, the median is the middle value. For example, in the dataset [1, 3, 5, 7, 9], the median is 5.

And,

E.g.: When the dataset has an even number of observations, the median is the average of the two middle values. For example, in the dataset [1, 3, 5, 7], the median is (3 + 5) / 2 = 4.

The median is a useful measure of central tendency because it is less sensitive to outliers compared to the mean, and it provides a robust measure of the typical value in a dataset.

Find the median of the two sorted arrays:

To find the median of two sorted arrays, you can merge the arrays and then calculate the median. Here's a JavaScript function to accomplish this:

js Copy Code
function findMedianSortedArrays(nums1, nums2) {
    const merged = mergeArrays(nums1, nums2);
    const n = merged.length;

    if (n % 2 === 0) {
        // If the merged array has even length
//return the average of the middle two elements
        const midRight = n / 2;
        const midLeft = midRight - 1;
        return (merged[midLeft] + merged[midRight]) / 2;
    } else {
        // If the merged array has odd length, return the middle element
        return merged[Math.floor(n / 2)];
    }
}

function mergeArrays(nums1, nums2) {
    const merged = [];
    let i = 0, j = 0;

    while (i < nums1.length && j < nums2.length) {
        if (nums1[i] <= nums2[j]) {
            merged.push(nums1[i]);
            i++;
        } else {
            merged.push(nums2[j]);
            j++;
        }
    }

    // Add remaining elements from nums1
    while (i < nums1.length) {
        merged.push(nums1[i]);
        i++;
    }

    // Add remaining elements from nums2
    while (j < nums2.length) {
        merged.push(nums2[j]);
        j++;
    }

    return merged;
}

// Example usage:
const nums1 = [1, 3, 5];
const nums2 = [2, 4, 6];
const median = findMedianSortedArrays(nums1, nums2);
console.log("Median:", median); // Output: Median: 3.5
Output:
3.5

Explanation:

This code first merges the two sorted arrays ('nums1' and 'nums2) into a single sorted array ('merged'). Then, it calculates the median of the merged array. If the merged array has an even length, it returns the average of the two middle elements. If the merged array has an odd length, it returns the middle element.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.