-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMedian of Two Sorted Arrays
51 lines (46 loc) · 1.21 KB
/
Median of Two Sorted Arrays
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
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size){
int first = 0;
int second = 0;
int median_index, i, j, k;
bool even = true;
if ((nums1Size + nums2Size) & 0x1)
even = false;
median_index = ((nums1Size + nums2Size)/2);
for (i=0, j=0, k=0; i <= median_index && j < nums1Size && k < nums2Size; i++)
{
if (nums1[j] < nums2[k])
{
first = second;
second = nums1[j];
j++;
}
else
{
first = second;
second = nums2[k];
k++;
}
}
if (i <= median_index)
{
/* ran out of one array */
if (j == nums1Size)
{
/* ran out of array1. just iterate thru array 2 until hitting median index */
for (; i <= median_index; i++, k++)
{
first = second;
second = nums2[k];
}
}
else
{
for (; i <= median_index; i++, j++)
{
first = second;
second = nums1[j];
}
}
}
return even ? ((double)(first + second))/2 : second;
}