Median Of Two Sorted Arrays
This algorithm finds the median of two sorted arrays by first getting medians of the two sorted arrays and then comparing them.
#define MIN(a, b) (a < b ? a : b)
#define MAX(a, b) (a > b ? a : b)
int Median(int* arr, int arrSize) {
if (arrSize % 2 == 0) return (arr[arrSize / 2] + arr[arrSize / 2 - 1]) / 2;
else return arr[arrSize / 2];
}
int GetMedian(int* arr1, int* arr2, int arrSize)
{
if (arrSize <= 0) return -1;
if (arrSize == 1) return (arr1[0] + arr2[0]) / 2;
if (arrSize == 2) return (MAX(arr1[0], arr2[0]) + MIN(arr1[1], arr2[1])) / 2;
int m1 = Median(arr1, arrSize);
int m2 = Median(arr2, arrSize);
if (m1 == m2) return m1;
if (m1 < m2) {
if (arrSize % 2 == 0) return GetMedian(arr1 + arrSize / 2 - 1, arr2, arrSize - arrSize / 2 + 1);
return GetMedian(arr1 + arrSize / 2, arr2, arrSize - arrSize / 2);
}
if (arrSize % 2 == 0) return GetMedian(arr2 + arrSize / 2 - 1, arr1, arrSize - arrSize / 2 + 1);
return GetMedian(arr2 + arrSize / 2, arr1, arrSize - arrSize / 2);
}
Example
int median = 0;
int arr1[] = { 1, 2, 3, 6 };
int arr2[] = { 4, 6, 8, 10 };
int arr1Size = sizeof(arr1) / sizeof(arr1[0]);
int arr2Size = sizeof(arr2) / sizeof(arr2[0]);
if (arr1Size == arr2Size)
median = GetMedian(arr1, arr2, arr1Size);
Output
median: 5