adnanadel
adnanadel

Reputation: 47

swap between rows in a 2D array in java

I am working on a java code that should swap between two 2d rows and I have completed it but I want to check if my work is correct and if it needs any modification to do.

import java.util.*;
public class Main {
    
    public static void printMatrix(int[][] matrix){
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++)
                System.out.print(matrix[i][j] + " ");
            System.out.println();
        }
    }
    public static void exchangeAnyTwoRows(int[][] matrix,
                                          int K, int L)
    {
        for (int i = 0; i < matrix[0].length; i++) {
            
            int temp = matrix[K - 1][i];
            matrix[K - 1][i] = matrix[L - 1][i];
            matrix[L - 1][i] = temp;
        }
        
        printMatrix(matrix);
    }
    
    public static void main(String[] args)
    {
        int K = 2, L = 3;
        int mat[][] = { { 2, 1, 4 }, { 1, 2, 3 }, { 3, 6, 2 } };
  
        exchangeAnyTwoRows(mat, K, L);
    }
}

any help would be really appreciated.

Upvotes: 0

Views: 319

Answers (1)

ntalbs
ntalbs

Reputation: 29458

Seems like you are swapping each element in the two rows. I don't think you need to do it in that way. You can just swap the rows at once:

  public static void exchangeAnyTwoRows(int[][] matrix, int r1, int r2) {
    int[] temp = matrix[r1];
    matrix[r1] = matrix[r2];
    matrix[r2] = temp;
  }

One other comment is that the above code will throw ArrayIndexOutOfBoundsException. The reason is that your row index starts from 1. You may decrease each index inside the method, however, just use 0 based indexes would be better to avoid confusion.

So, you may want to modify the values of K and L to 1 and 2, respectively.

Upvotes: 1

Related Questions