# Java Program to Find Median of Two Arrays of Different Sizes

This is a java program to find the median from two different array. To do so we merge the two lists and then sort them, after that we find the median of the sequence. If the total number of elements (N) is odd median is the N/2th element, if its even (N-1/2 + N/2)/2th element.

Here is the source code of the Java Program to Find Median of Elements where Elements are Stored in 2 Different Arrays. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

1. `//This is a java program to find the median of 2 array`
2. `import java.util.Random;`
3. ` `
4. `public class Median_Two_Arrays `
5. `{`
6. `    static int N = 10, M = 5;`
7. `    static int[] sequence1 = new int[N];`
8. `    static int[] sequence2 = new int[M];`
9. `    static int[] sequence = new int[N+M];`
10. ` `
11. `    public static void sort() `
12. `    {`
13. `        int i, j, temp;`
14. `        for (i = 1; i < N+M; i++) `
15. `        {`
16. `            j = i;`
17. `            temp = sequence[i];`
18. `            while (j > 0 && temp < sequence[j - 1]) `
19. `            {`
20. `                sequence[j] = sequence[j - 1];`
21. `                j = j - 1;`
22. `            }`
23. `            sequence[j] = temp;`
24. `        }`
25. `    }`
26. ` `
27. `    public static void main(String args[])`
28. `    {`
29. `        Random random = new Random();`
30. ` `
31. `        for(int i=0; i<N; i++)`
32. `            sequence1[i] = Math.abs(random.nextInt(100));`
33. `        for(int i=0; i<M; i++)`
34. `            sequence2[i] = Math.abs(random.nextInt(100));`
35. `        for(int i=0; i<N; i++)`
36. `            System.out.print(sequence1[i] + " ");`
37. `        System.out.println();`
38. ` `
39. `        for(int i=0; i<M; i++)`
40. `            System.out.print(sequence2[i] + " ");`
41. `        System.out.println();`
42. ` `
43. ` `
44. `        int j=0;`
45. `        for(int i=0; i<N+M; i++)`
46. `        {`
47. `            if(i >= N && j < M)`
48. `                sequence[i] = sequence2[j++];`
49. `            else`
50. `                sequence[i] = sequence1[i];`
51. `        }`
52. ` `
53. `        sort();`
54. ` `
55. `        if(N+M % 2 == 0)`
56. `            System.out.println("The Median is : " + (sequence[(N+M)/2-1]+sequence[(N+M)/2])/2);`
57. `        else`
58. `            System.out.println("The Median is : " + sequence[(N+M)/2]);`
59. `    }`
60. `}`

Output:

```\$ javac Median_Two_Arrays.java
\$ java Median_Two_Arrays

92 53 68 15 17 23 95 47 46 61
63 62 48 66 26
The Median is : 53```

Sanfoundry Global Education & Learning Series – 1000 Java Programs.