Link copied to clipboard. Share away!

Dissmis

Published on 09 Mar 2020

Program to find the median of two sorted arrays of same size and different size are discussed here. Firstly, let us see what is median of the array?

Median is an element which divides the array into two parts - left and right. So the number of elements on the left side of the array will be equal or less than the number of elements on the right side. Now, let us consider the case of an array with odd number of elements.

**Array = [9,11,16,7,2]**

**Sorted array = [2,7,9,11,16]**

In this case, the median of this array is 9, since it divides the array into two parts: [2,7] and [11,16].

Further, let us consider the case of an array with even elements.

**Array = [1,2,3,4,5,6]**

In such a case, we will take the average between the last element of the left part and the first element of the right part. In this case, the median equals = (3 + 4) / 2 = 3.5

Let us assume that there are 2 sorted arrays A and B of size n each.Write an algorithm to find the median of the array obtained after merging the above 2 arrays(i.e. array of length 2n).

```
Test cases
Input:
5
1 12 15 26 38
2 13 17 30 45
Output:
16
Explanation: After merging two arrays, we get {1, 2, 12, 13, 15, 17, 26, 30, 38, 45}
Middle two elements are 15 and 17
Average of middle two elements is (15+17)/2 = 16.
```

```
Asked in recruitment drive of Paypal, Flipkart etc.
```

C

C++

Java

Python 3

Output

Input-
Enter the size:5
Enter the first Array elements:
1
12
15
26
38
Enter the Second Array elements:
2
13
17
30
45
Output-
Median:16

C

C++

Output

Input-
Enter the size:5
Enter the first Array elements:
1
12
15
26
38
Enter the Second Array elements:
2
13
17
30
45
Output-
Median:16

*Recommended Programs*

If you have any feedback about this
article and want to improve this, please write to **enquiry@faceprep.in**

×