【发布时间】:2016-08-24 14:22:35
【问题描述】:
在我的代码中,我在第一行收到值 n 和 d。 N 将是我要写入的值的数量,d 是每个位置 n 中的数字数量。 所以在接下来的 n 个值中,我引入了 d 个值。这个练习的重点是使用插入排序,但如果第一个坐标相等,它将比较第二个,如果再次发生这种情况,则比较第三个,依此类推。例子: 输入:
5 3
1 1 1
1 0 1
1 1 0
0 1 1
0 1 0
输出:
0 1 0
0 1 1
1 0 1
1 1 0
1 1 1
这是我的代码:
public static void main(String[] args) {
int n,d,aux;
Scanner sc = new Scanner( System.in );
n = sc.nextInt();
d = sc.nextInt();
int tab [][] = new int[n][d];
for(int i=0;i<n;i++){
for(int j=0;j<d;j++){
aux = sc.nextInt();
tab[i][j] = aux;
}
}
insertionSort(tab,d);
System.out.println("---");
for(int u=0;u<tab.length;u++){
for(int y=0;y<d;y++){
System.out.print(tab[u][y]+" ");
}
System.out.println();
}
}
public static void insertionSort(int tab[][],int d){
int i,j;
int pos = 0;
int tmp [][] = new int[1][d];
for(i = 1;i < tab.length;i++)
{
for(int k=0;k<d;k++)
tmp[0][k] = tab[i][k];
for(j = i; j>0 && tmp[0][0] <= tab[j-1][0];j--)
{
while(tmp[0][pos] == tab[j-1][pos] && pos+1<d){
pos++;
if(tmp[0][pos] < tab[j-1][pos]){
pos=0;
break;
}
}
if(pos==0){
for(int k=0;k<d;k++)
tab[j][k] = tab[j-1][k];
}
}
for(int k=0;k<d;k++)
tab[j][k] = tmp[0][k];
pos = 0;
}
}
问题是我的输出错误:
0 1 0
0 1 1
1 1 0
1 1 1
1 1 1
【问题讨论】:
-
打印数组的代码在哪里?我看不到它
-
我现在放,我会编辑
-
你知道怎么回事吗?
-
问题是如果他们不需要改变,在for cicle的末尾无论如何都会改变。但是我也尝试设置一个条件,但是如果一个位置改变而第二个不需要,它不会改变第一个位置,因为第二个不需要改变,如果我把那个条件放在那里,它就不会做决赛。有什么帮助吗?
标签: java multidimensional-array insertion-sort