英文:
Sorting 2d Integers Array Java
问题
我有一个2D数组,大小为[2][10]。它被填充了随机数字。
请问有人可以帮助我如何对其进行排序吗?不知道为什么,但任何找到的使用Comparator来排序的方法都不适用于我。所以我正在尝试使用循环来排序它。它必须按列排序。
我试图创建一个临时数组并将值插入其中,但我不知道如何比较[0][0]和[0][1]的值。
我的尝试是使用两个for循环,并在其中进行比较:
for (int i = 0; i < arr4.length; i++) {
for(int j = 0; j < arr4[i].length; j++) {
if(arr4[i][j] > ???????)
temparray = arr4[i][j];
}
}
请帮帮我...
英文:
i have an 2d Array which is [2][10]. It is filled with random numbers.
Could someone please help me how to sort it? I dont know why but any found way to sort it with Comparator doesnt work for me. So im trying to do that in a loop. It has to be sorted by the column.
Im trying to play with creating a temporary array and inserting the value into it, but i dont know how to compare values: [0][0] and [0][1].
My try is do 2 for loops and inside it:
for (int i = 0; i < arr4.length; i++) {
for(int j = 0; j < arr4[i].length; j++) {
if(arr4[i][j] > ???????)
temparray = arr4[i][j];
}
}
Help me please...
答案1
得分: 1
// 如果需要逐行排序,您需要按以下方式更新您的解决方案
for (int i = 0; i < arr4.length; i++) {
for(int j = 0; j < arr4[i].length-1; j++) {
if(arr4[i][j] > arr4[i][j+1]){
temparray = arr4[i][j];
arr4[i][j] = arr4[i][j+1]
arr4[i][j+1] = temparray ;
j=0;
}
}
}
输入:
[1.0, 2.0]
[6.0, 4.0]
[5.0, 4.0]
输出:
[1.0, 2.0]
[4.0, 6.0]
[4.0, 5.0]
英文:
if you need to sort line by line you need to update your solution like this
for (int i = 0; i < arr4.length; i++) {
for(int j = 0; j < arr4[i].length-1; j++) {
if(arr4[i][j] > arr4[i][j+1]){
temparray = arr4[i][j];
arr4[i][j] = arr4[i][j+1]
arr4[i][j+1] = temparray ;
j=0;
}
}
}
input:
[1.0, 2.0]
[6.0, 4.0]
[5.0, 4.0]
output:
[1.0, 2.0]
[4.0, 6.0]
[4.0, 5.0]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论