Je dois créer un code qui trie les tableaux 2D. L'astuce ici est que je ne peux pas utiliser un assistant de tableau unidimensionnel ou déplacer les éléments vers un autre tableau.
Le tri doit être sur le tableau 2D.
Maintenant, j'ai construit ma fonction. Mais quelque chose ne va pas. Ceci est ma sortie
1 1 2 6 12 32
49 44 54 55 100 344
est près d'être fait, et je ne peux pas penser comment le faire.
public static int [] [] sortMatrix(int[][]matrix){
for(int x = matrix.length ; x >0 ; x-- ){
for(int i = matrix[0].length ; i > 0 ; i-- ){
for(int j = 0 ; j < x ; j++){
for(int t = 0 ;t < i ; t++){
if(t < matrix[0].length - 1 && matrix[j][t] > matrix[j][t+1] ){
swap(matrix , j , t, t+1);
}
else if(t == matrix[0].length - 1 && j != matrix.length -1&& matrix[j][t] > matrix[j+1][0] ){
swap1(matrix ,j , t , j + 1);
}
}
}
}
}
Réponses:
0 pour la réponse № 1Vous trouverez ci-dessous le code de tri des tableaux 2D. Vous devez penser au tableau 2D comme un tableau à une dimension, puis dériver la ligne appropriée, les paires de décalage pour les index.
import java.util.Arrays;
public class Bubble2DSort {
public static void main(String[] args) {
System.out.println("Started");
int[][] matrix = {{49,44,54,55,100,344}, {1,1,2,6,12,32}};
sortMatrix(matrix);
System.out.println("Printing output ");
for(int[] rowArr : matrix) {
System.out.println(Arrays.toString(rowArr));
}
}
private static void sortMatrix(int[][] matrix) {
int row = matrix.length;
int col = matrix[0].length;
int totalCount = row * col;
System.out.println("totalCount : " +totalCount);
boolean noSwaps = false;
for(int i = 0; !noSwaps; i++) {
noSwaps = true;
for(int j = 1; j < totalCount - i; j++) {
int currentRow = (j-1) / col;
int currentOffset = (j-1) % col;
int nextRow = j / col;
int nextOffset = j % col;
if( matrix[currentRow][currentOffset] > matrix[nextRow][nextOffset]) {
//swapping
int temp = matrix[nextRow][nextOffset];
matrix[nextRow][nextOffset] = matrix[currentRow][currentOffset];
matrix[currentRow][currentOffset] = temp;
noSwaps = false;
}
}
}
}
}
Sortie:
Started
totalCount : 12
Printing output
[1, 1, 2, 6, 12, 32]
[44, 49, 54, 55, 100, 344]