-
Notifications
You must be signed in to change notification settings - Fork 617
/
overall_median_matrix.java
127 lines (112 loc) · 2.3 KB
/
overall_median_matrix.java
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/*
* To find the overall median of a matrix
*
* Example:
*
* A = [ [1, 3, 5],[2, 6, 9],[3, 6, 9] ]
*
* output: 5
*
* Explanation:
* Total elements we have
* 1,2,3,3,5,6,6,9,9
* here there are 9 elements and median would be (n+1)/2 = 4th term
*
* 4th term = 5
*
*/
import java.util.*;
public class overall_median_matrix
{
public void main()
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number of rows: ");
int m = scanner.nextInt(); scanner.nextLine();
System.out.println("Enter number of columns: ");
int n = scanner.nextInt(); scanner.nextLine();
int A[][] = new int[m][n];
int i, j, count = 0, temp, index;
System.out.println("Enter elements: ");
//accpeting values in matrix from user
for(i = 0; i < m; i ++)
{
for(j = 0; j < n; j ++)
{
A[i][j] = scanner.nextInt(); scanner.nextLine();
}
}
int flatA[] = new int[m*n];
//converting matrix into one dimensional array
for(i = 0; i < m; i ++)
{
for(j = 0; j < n; j ++)
{
flatA[count] = A[i][j];
count++;
}
}
//sorting the one dimensional array
for(i = 0; i < m * n - 1; i++)
{
for(j = 0; j < m * n - i - 1; j++)
{
if(flatA[j] > flatA[j+1])
{
temp = flatA[j];
flatA[j] = flatA[j+1];
flatA[j+1] = temp;
}
}
}
if(m * n % 2 == 0)
{
index = ((m * n) / 2) - 1;
}
else
{
index = (((m * n) + 1) / 2) - 1;
}
System.out.println("Median is: "+flatA[index]);
}
}
/*
* Test Cases-
*
* 1.
* Enter number of rows:
* 3
* Enter number of columns:
* 3
* Enter elements:
* 1
* 3
* 5
* 2
* 6
* 9
* 3
* 6
* 9
* Median is: 5
*
* 2.
* Enter number of rows:
* 2
* Enter number of columns:
* 4
* Enter elements:
* 1
* 3
* 7
* 2
* 3
* 9
* 7
* 6
* Median is: 3
*
* Time Complexity: O(m*n)
* Space Complexity: O(m*n)
* where m in number of rows and n is number of columns
*/