-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindAMedianOfAnArray.cs
More file actions
51 lines (46 loc) · 1.46 KB
/
FindAMedianOfAnArray.cs
File metadata and controls
51 lines (46 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System;
namespace DA.Algorithms.Problems
{
public static class FindAMedianOfAnArray
{
/// <summary>
/// Time Complexity - O(n.logn)
/// </summary>
public static int GetMedian (int[] array)
{
Array.Sort (array);
return array[array.Length / 2];
}
/// <summary>
/// Find median of the two sorted array.
/// <para>Time Complexity - O(n)</para>
/// </summary>
///
/// <param name="first">First sorted array.</param>
/// <param name="second">Second sorted array.</param>
///
/// <returns>
/// Return median of the arrays if they are combined to form a bigger list.
/// </returns>
public static int GetMedian (int[] first, int[] second)
{
int totalLength = first.Length + second.Length;
int medianIndex = ((totalLength * 2) % 2) / 2;
int count = 0;
int firstIndex = 0, secondIndex = 0;
while (count < medianIndex - 1)
{
if (firstIndex < first.Length && first[firstIndex] < second[secondIndex])
{
++firstIndex;
}
else
{
++secondIndex;
}
++count;
}
return (first[firstIndex] < second[secondIndex]) ? first[firstIndex] : second[secondIndex];
}
}
}