Created
July 26, 2013 06:20
-
-
Save riyadparvez/6086705 to your computer and use it in GitHub Desktop.
Get median of two sorted arrays in C#.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public static double GetMedian(IEnumerable<double> list1, IEnumerable<double> list2) | |
| { | |
| var arr1 = list1.ToArray(); | |
| var arr2 = list2.ToArray(); | |
| if(arr1.Length == 2 && arr2.Length == 2) | |
| { | |
| return (Math.Max(arr1[0], arr2[0]) + Math.Min(arr1[1], arr2[1]))/2; | |
| } | |
| int mid1 = arr1.Length/2; | |
| int mid2 = arr2.Length/2; | |
| if(arr1[mid1] < arr2[mid2]) | |
| { | |
| return GetMedian(arr1.Skip(mid1), arr2.Take(mid2)); | |
| } | |
| else if (arr1[mid1] > arr2[mid2]) | |
| { | |
| return GetMedian(arr1.Take(mid1), arr2.Skip(mid2)); | |
| } | |
| else | |
| { | |
| return arr1[mid1]; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment