Friday, July 24, 2026
HomeLanguagesJavaJava Program to Interchange Any Two Rows in the Matrix

Java Program to Interchange Any Two Rows in the Matrix

Given a matrix having m rows and n columns. We have to write a Java program to interchange any two Rows in the given matrix. Swap Operation is required to interchange the elements of two rows. O(1) operation to swap two rows is impossible because complete traversal between two rows is required.

Examples

Input 1: K = 1, L = 2,

          mat[][] = {{2, 1, 4},
                     {1, 2, 3},  
                     {3, 6, 2}}
                     
Output: 
          mat[][] = {{1, 2, 3},
                     {2, 1, 4},  
                     {3, 6, 2}}
                    

Input 2: K = 1, L = 1,
          mat[][] = {{2, 1, 4},
                     {1, 2, 3}} 
                              
Output: 
          mat[][] = {{2, 1, 4},
                     {1, 2, 3}}   
                                   
Input 3: K = 2, L = 3,
          mat[][] =  {{2, 1},
                      {1, 2},  
                      {3, 6}}
                     
Output: 
          mat[][] =  {{2, 1},
                     {3, 6},  
                     {1, 2}}

Approach

  • If First and Second are same, then print the matrix as it is.
  • Else Loop over the Kth and Lth row of the matrix.
  • Swap the elements ith index of both the rows while traversal.
  • Now after the loop gets over, print the matrix.

Below is the code implementation for the above approach:

Java




// Java program to interchange
// two row in a Matrix
import java.io.*;
 
class GFG {
   
    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)
    {
         
        int[] temp = matrix[K - 1];
        matrix[K - 1]= matrix[L - 1];
        matrix[L - 1] = temp;
       
        // Print matrix
        printMatrix(matrix);
    }
   
    public static void main(String[] args)
    {
        int K = 2, L = 3;
        int mat[][] = { { 2, 1, 4 }, { 1, 2, 3 }, { 3, 6, 2 } };
 
        // calling the exchange row function
        exchangeAnyTwoRows(mat, K, L);
    }
}


 
 

Output

2 1 4 
3 6 2 
1 2 3 

 

Time Complexity: 0(n), Where n is the length of the row.

 

Space Complexity: 0(1)

 

RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32520 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6902 POSTS0 COMMENTS
Nicole Veronica
12017 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12115 POSTS0 COMMENTS
Shaida Kate Naidoo
7023 POSTS0 COMMENTS
Ted Musemwa
7265 POSTS0 COMMENTS
Thapelo Manthata
6980 POSTS0 COMMENTS
Umr Jansen
6971 POSTS0 COMMENTS