Java 插入排序与二维数组
我正在尝试使用插入排序来按每行的第一列值对Java中的2D数组进行排序。我已经在一个大小为2的数组上测试了它,但是当我尝试大小为3的代码时,它甚至没有运行for循环。谢谢你能给我的帮助Java 插入排序与二维数组,java,arrays,2d,Java,Arrays,2d,我正在尝试使用插入排序来按每行的第一列值对Java中的2D数组进行排序。我已经在一个大小为2的数组上测试了它,但是当我尝试大小为3的代码时,它甚至没有运行for循环。谢谢你能给我的帮助 public int[][] sortC(int[][] temp) { if (temp.length == 1) { return temp; } else if (temp.length >=
public int[][] sortC(int[][] temp)
{
if (temp.length == 1)
{
return temp;
}
else if (temp.length >= 2)
{
for (int i = 1; i <= temp.length - 1; i++)
{
int holdRow = temp[i][0];
int holdCol = temp[i][1];
// hold past index
int holdRowP = temp[i - 1][0];
int holdColP = temp[i - 1][1];
int j = i;
while (j > 0 && holdRow < holdRowP)
{
holdRow = temp[j][0];
holdCol = temp[j][1];
// hold past index
holdRowP = temp[j - 1][0];
holdColP = temp[j - 1][1];
// make single swap
temp[j][0] = holdRowP;
temp[j][1] = holdColP;
temp[j-1][0] = holdRow;
temp[j-1][1] = holdCol;
j--;
}
}
}
return temp;
}
public int[]sortC(int[]temp)
{
如果(温度长度==1)
{
返回温度;
}
否则如果(温度长度>=2)
{
对于(int i=1;i 0&&holdRow
通过使用Java 2D数组实际上是数组的数组这一事实,您可以简化很多,并使其适用于任意大小。内部数组(即行)可以作为整体单元移动,而不是像您这样零碎地移动
当您的代码修改传递的参数时,也不需要返回数组
调用sortC(input)
后,input
数组将被排序
使用这两种方法,您的代码可以简化为
public void sortC(int[][] temp)
{
if (temp.length >= 2)
{
for (int i = 1; i <= temp.length - 1; i++)
{
int[] hold = temp[i];
int[] holdP = temp[i-1];
int j = i;
while (j > 0 && hold[0] < holdP[0])
{
hold = temp[j];
holdP = temp[j-1];
temp[j] = holdP;
temp[j-1] = hold;
j--;
}
}
}
}
public void sortC(int[]temp)
{
如果(温度长度>=2)
{
对于(int i=1;i 0&&hold[0]