[英]Sorting a 2d array in ascending order
我試圖從{4,2},{1,7},{4,5},{1,2},{1,1},{4,1}
到這個以升序對這個二維數組進行排序{1,1},{1,2},{1,7},{4,1},{4,2},{4,5}
. 但出於某種原因,它仍然給了我原始數組並且沒有排序。 我錯過了什么?
public class Sort {
public static void main(String[] args) {
int[][] array = {{4, 2}, {1, 7}, {4, 5}, {1, 2}, {1, 1}, {4, 1}};
sort(array);
print(array);
}
//Row Length
public static void print(int[][] m) {
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++) {
System.out.print("{" + m[i][j] + "}" + " ");
}
System.out.println();
}
}
public static int sort(int A[][]) {
int newArray = 0;
for (int i = 0; i < A.length; i++) {
for (int j = i + 1; j < A[i].length - 1; j++) {
if (A[j][0] > A[j + 1][0]) {
int temp = 0;
temp = A[i][j];
A[i][j] = A[i + 1][j + 1];
A[i + 1][j + 1] = A[i][j];
System.out.print(" " + A[i][j]);
}
}
}
return newArray;
}
}
這做你想要的:
您的 if 語句從未執行過,因為在進行比較時您的邏輯是錯誤的。
因此,您的原始代碼中從未設置過 temp。
最重要的是, temp
應該是一個int[]
,而不是一個int
。
也不需要從 sort 方法返回int
。
我還稍微調整了您的打印程序。
import static java.lang.System.out;
public class Playground {
public static void main(String[] args) {
int[][] array = {{4, 2}, {1, 7}, {4, 5}, {1, 2}, {1, 1}, {4, 1}};
sort(array);
print(array);
}
public static void print(int[][] m) {
for (int i = 0; i < m.length; i++) {
if (i > 0) {
out.print(",");
}
out.print("{" + m[i][0] + "," + m[i][1] + "}");
}
out.println();
}
public static void sort(int A[][]) {
boolean unsorted = true;
while (unsorted) {
unsorted = false;
for (int i = 0; i < A.length - 1; i++) {
if ((A[i][0] > A[i + 1][0])
|| ((A[i][0] == A[i + 1][0])
&& (A[i][1] > A[i + 1][1])
)) {
int[] temp = new int[2];
temp[0] = A[i][0];
temp[1] = A[i][1];
A[i][0] = A[i + 1][0];
A[i][1] = A[i + 1][1];
A[i + 1] = temp;
unsorted = true;
}
}
}
}
}
你可以看到它在這里運行。
您可以使用比較器鏈接首先按一列sort
,然后按另一列sort
:
int[][] array = {{4, 2}, {1, 7}, {4, 5}, {1, 2}, {1, 1}, {4, 1}};
Arrays.sort(array, Comparator
.<int[]>comparingInt(arr -> arr[0])
.thenComparing(arr -> arr[1]));
System.out.println(Arrays.deepToString(array));
// [[1, 1], [1, 2], [1, 7], [4, 1], [4, 2], [4, 5]]
另請參閱:按多列中的值對二維數組進行排序
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.