C program to find the median of two sorted arrays with same using simple merge-based O(n) solution

Here, we are going to learn how to find the median of two sorted arrays with same using simple merge-based O(n) solution in C programming language?
Submitted by Nidhi, on July 12, 2021

Problem Solution:

Here, we will create two sorted arrays of the same size. And, we used a simple merge-based O(n) solution and print the median on the console screen.

Program:

The source code to find the median of two sorted arrays with the same using a simple merge-based O(n) solution is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

```// C program to find the median of two arrays
// using a simple merge-based O(n) solution

#include <stdio.h>

int calculateMedian(int arr1[], int arr2[], int size)
{
int i = 0;
int j = 0;

int med1 = -1;
int med2 = -1;

int loop = 0;

for (loop = 0; loop <= size; loop++) {
if (i == size) {
med1 = med2;
med2 = arr2[0];
break;
}
else if (j == size) {
med1 = med2;
med2 = arr1[0];
break;
}

if (arr1[i] <= arr2[j]) {
med1 = med2;
med2 = arr1[i];
i++;
}
else {
med1 = med2;
med2 = arr2[j];
j++;
}
}

return (med1 + med2) / 2;
}

int main()
{
int arr1[] = { 10, 11, 12, 13, 14 };
int arr2[] = { 21, 22, 23, 24, 25 };

int size1 = sizeof(arr1) / sizeof(arr1[0]);
int size2 = sizeof(arr2) / sizeof(arr2[0]);

if (size1 != size2) {
printf("Size of both arrays are different\n");
return 0;
}

printf("Median is: %d\n", calculateMedian(arr1, arr2, size1));

return 0;
}
```

Output:

```Median is: 17
```

Explanation:

Here, we created two arrays arr1, arr2 with 5 integer elements. And, we find the median of both arrays using the simple merge O(n) method. And, we also checked with the size of both arrays is different, then print the error message, and calculateMedian() function to calculate the median and return the result to the main() function. After that, we printed the result on the console screen.