Program to find the median of two sorted arrays | faceprep

Program to find the median of two sorted arrays | faceprep

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


Program to find the median of two sorted arrays

A 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 to or less than the number of elements on the right side. Now, let us consider the case of an array with an 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.


Program to find the median of two sorted arrays

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


The median of two sorted arrays of the same size


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 casesnnInput:n5n1 12 15 26 38n2 13 17 30 45nnOutput:n16nnExplanation: After merging two arrays, we get {1, 2, 12, 13, 15, 17, 26, 30, 38, 45}nMiddle two elements are 15 and 17nAverage of middle two elements is (15+17)/2 = 16.n


Asked in recruitment drive of Paypal, Flipkart etc.n


@@coding::1@@



Program to find the median of two sorted arrays

The median of two sorted arrays of different size


@@coding::2@@



Recommended Programs







Program to find the median of two sorted arrays

c