-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMedian of 2 sorted arrays of different size
56 lines (47 loc) · 1.26 KB
/
Median of 2 sorted arrays of different size
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
52
53
54
55
56
//{ Driver Code Starts
//Initial Template for Java
import java.util.*;
import java.lang.*;
import java.io.*;
class Driver
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int []a = new int[n];
for (int i = 0; i < n; i++) a[i] = sc.nextInt();
int m= sc.nextInt();
int []b = new int[m];
for (int i = 0; i < m; i++) b[i] = sc.nextInt();
double res = new GFG().medianOfArrays(n, m, a, b);
if (res == (int)res) System.out.println ((int)res);
else System.out.println (res);
}
}
}
// } Driver Code Ends
//User function Template for Java
class GFG
{
static double medianOfArrays(int n, int m, int a[], int b[])
{
int[] arr = new int[n+m];
for(int i=0; i<n; i++)
{
arr[i]=a[i];
}
for(int i=0; i<m; i++)
{
arr[n+i]=b[i];
}
Arrays.sort(arr);
if(arr.length%2==0)
{
return (double)(arr[arr.length/2]+arr[(arr.length/2)-1])/2;
}
return (double)arr[arr.length/2];
}
}