There are 2 sorted arrays A and B of size n each. Write an algorithm to find the median of the array obtained merging the above 2 arrays(i.e. array of length 2n). The complexity should be O(log(n)).
Note : Since size of the set for which we are looking for median is even (2n), we need take average of middle two numbers and return floor of the average.
Method 1 (Simply count while Merging)
Use merge procedure of merge sort. Keep track of count while comparing elements of two arrays. If count becomes n(For 2n elements), we have reached the median. Take the average of the elements at indexes n-1 and n in the merged array. See the below implementation.
Median is 16
Method 2 (By comparing the medians of two arrays)
This method works by first getting medians of the two sorted arrays and then comparing them.
Median is 5
Please refer complete article on Median of two sorted arrays of same size for more details!
- C Program to Find the closest pair from two sorted arrays
- C Program to find size of a File
- C Program for Maximum size square sub-matrix with all 1s
- C/C++ program to find the size of int, float, double and char
- C Program for Program to find area of a circle
- Lex Program to remove comments from C program
- C Program for Program for array rotation
- size of char datatype and char array in C
- Performance analysis of Row major and Column major order of storing arrays in C
- How does a C program executes?
- C Program to Add two Integers
- C Hello World Program
- C Program for Cutting a Rod | DP-13
- C Program for ID3 Tagging
- Program to print Hut