*A Simple & efficient Algorithm Will be as Follow
*
Algorithm:
let ar1,ar2 be the two sorted array of integers (for simplicity assume both
has same length)
1) Calculate the medians m1 and m2 of the input arrays ar1[]
and ar2[] respectively.
2) If m1 and m2 both are equal then we are done.
return m1 (or m2)
3) If m1 is greater than m2, then median is present in one
of the below two subarrays.
a) From first element of ar1 to m1 (ar1[0 to floor(n/2)])
b) From m2 to last element of ar2 (ar2 [floor(n/2) to n-1])
4) If m2 is greater than m1, then median is present in one
of the below two subarrays.
a) From m1 to last element of ar1 (ar1[floor(n/2) to n-1])
b) From first element of ar2 to m2 (ar2[0 to floor(n/2) ])
5) Repeat the above process until size of both the subarrays
becomes 2.
6) If size of the two arrays is 2 then use below formula to get
the median. Median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2
7. if size of two array is 1 then return Median=(ar1[0] + ar2[0])/2;
*Time Complexity O(logn) where n is length array
2nd Algorithm
Use same Idea we used to solve kth Order statistics in array , e.g. to find
kth maximum or minimum in union of two sorted array.its little bit complex
but efficient same as above.
Algorithm:
*The basic idea is that if you are given two arrays ar1[] and ar2[] and know
the length of each, you can check whether an element ar1[i] is the median in
constant time. Suppose that the median is ar1[i]. Since the array is sorted,
it is greater than exactly i-1 values in array ar1[]. Then if it is the
median, it is also greater than exactly j = n – i – 1 elements in ar2[].
It requires constant time to check if ar2[j] <= ar1[i] <= ar2[j + 1]. If
ar1[i] is not the median,
then depending on whether ar1[i] is greater or less than ar2[j] and ar2[j +
1], you know that ar1[i] is either greater than or less than the median.
Thus you can binary search for median in O(lg n) worst-case time.
*Time Complexity O(logn) where n is length array *
*
Thanks
Shashank Mani
Computer Science
Birla Institute of Technology Mesra*
--
You received this message because you are subscribed to the Google Groups
"Algorithm Geeks" group.
To view this discussion on the web visit
https://groups.google.com/d/msg/algogeeks/-/Rm938TwkXGEJ.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/algogeeks?hl=en.