Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP Program for Median of two Sorted Arrays of Same Size
The median is a value that separates the higher half from the lower half of a data set. When finding the median of two sorted arrays of the same size, we need to merge them conceptually and find the middle elements. This can be done efficiently using a merge-based approach without actually creating a new merged array.
Algorithm Approach
The solution uses two pointers to traverse both arrays simultaneously, keeping track of the two middle elements needed to calculate the median. Since we have 2n total elements, the median will be the average of elements at positions n-1 and n in the conceptually merged array.
Example
Here's a PHP implementation to find the median of two sorted arrays ?
<?php
// Function to find median of two sorted arrays of same size
function getMedian($ar1, $ar2, $n)
{
$i = 0; // Index for first array
$j = 0; // Index for second array
$m1 = -1; // Previous median element
$m2 = -1; // Current median element
// We need to find elements at position n-1 and n
// in the merged array (0-indexed)
for ($count = 0; $count <= $n; $count++)
{
// If all elements of ar1[] are processed
if ($i == $n)
{
$m1 = $m2;
$m2 = $ar2[$j];
break;
}
// If all elements of ar2[] are processed
else if ($j == $n)
{
$m1 = $m2;
$m2 = $ar1[$i];
break;
}
// Compare current elements and move pointer
if ($ar1[$i] < $ar2[$j])
{
$m1 = $m2;
$m2 = $ar1[$i];
$i++;
}
else
{
$m1 = $m2;
$m2 = $ar2[$j];
$j++;
}
}
return ($m1 + $m2) / 2;
}
// Test arrays
$ar1 = array(1, 3, 5, 7, 9, 11);
$ar2 = array(2, 4, 6, 8, 10, 12);
$n = count($ar1);
if (count($ar1) == count($ar2))
{
$median = getMedian($ar1, $ar2, $n);
echo "Array 1: " . implode(", ", $ar1) . "<br>";
echo "Array 2: " . implode(", ", $ar2) . "<br>";
echo "Median is: " . $median;
}
else
{
echo "Arrays must have the same size";
}
?>
Array 1: 1, 3, 5, 7, 9, 11 Array 2: 2, 4, 6, 8, 10, 12 Median is: 6.5
How It Works
The algorithm works by simulating the merge process of two sorted arrays without actually creating the merged array. It keeps track of two variables:
- m1 The element at position n-1 in the merged array
- m2 The element at position n in the merged array
The median is calculated as (m1 + m2) / 2, which gives us the average of the two middle elements in the conceptually merged array of size 2n.
Time and Space Complexity
| Complexity | Value | Explanation |
|---|---|---|
| Time | O(n) | Single pass through both arrays |
| Space | O(1) | Only a few variables used |
Conclusion
This merge-based approach efficiently finds the median of two sorted arrays in O(n) time complexity. The algorithm simulates merging without creating additional arrays, making it space-efficient while maintaining accuracy in median calculation.
