# 排序二维整数数组 Java

go评论71阅读模式

Sorting 2d Integers Array Java

# 问题

``````for (int i = 0; i &lt; arr4.length; i++) {
for(int j = 0; j &lt; arr4[i].length; j++) {
if(arr4[i][j] &gt; ???????)
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 &lt; arr4.length; i++) {
for(int j = 0; j &lt; arr4[i].length; j++) {
if(arr4[i][j] &gt; ???????)
temparray = arr4[i][j];
}
}
``````

# 答案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 &lt; arr4.length; i++) {
for(int j = 0; j &lt; arr4[i].length-1; j++) {
if(arr4[i][j] &gt; 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]
``````

• 本文由 发表于 2020年10月1日 23:52:32
• 转载请务必保留本文链接：https://go.coder-hub.com/64158942.html
• 2d
• arrays
• java

go 49

go 70

go 73