median of array
Median
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
Median of two sorted arrays of 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 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.
Comments