4
在我的代碼中,我在第一行收到值n和d。 N將是我想要寫入的值的數量,d是每個位置n中的數字的數量。 因此,在接下來的n個值中,我引入了d值。這個練習的要點是使用插入排序,但如果第一個座標相等,則比較第二個,如果再次發生,則比較第三個,依此類推。例如: 輸入:使用多維數組的InsertionSort
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
其中,是代碼打印數組?我不能看到它 – piyushj
我會把它現在,我會編輯 –
你知道什麼是錯的嗎? –