-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathExercise08_16.java
58 lines (44 loc) · 1.57 KB
/
Exercise08_16.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
package ch_08;
/*
*8.16 (Sort two-dimensional array) Write a method to sort a two-dimensional array
using the following header:
public static void sort(int m[][])
The method performs a primary sort on rows and a secondary sort on columns.
For example, the following array
{{4, 2},{1, 7},{4, 5},{1, 2},{1, 1},{4, 1}}
will be sorted to
{{1, 1},{1, 2},{1, 7},{4, 1},{4, 2},{4, 5}}.
*/
import java.util.Arrays;
public class Exercise08_16 {
public static void main(String[] args) {
int[][] testArray = {{4, 2}, {1, 7}, {4, 5}, {1, 2}, {1, 1}, {4, 1}};
sort(testArray);
}
public static void sort(int m[][]) {
for (int i = 0; i < m.length - 1; i++) {
int currentMinRow = m[i][0];
int currentMinCol = m[i][1];
int currentMinIndex = i;
for (int j = i + 1; j < m.length; j++) {
if (currentMinRow > m[j][0]) {
currentMinRow = m[j][0];
currentMinCol = m[j][1];
currentMinIndex = j;
} else if (currentMinRow == m[j][0] && currentMinCol > m[j][1]) {
currentMinCol = m[j][1];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
m[currentMinIndex][0] = m[i][0];
m[i][0] = currentMinRow;
m[currentMinIndex][1] = m[i][1];
m[i][1] = currentMinCol;
}
}
for (int i = 0; i < m.length; i++) {
System.out.print(Arrays.toString(m[i]) + " ");
}
}
}