Sort Matrix Column-wise in Java

Write a program to allow the user to enter integers into a two-dimensional array of size M × N.

The size of the rows and columns is also entered by the user.

Display the original matrix.

Now sort the integers column-wise in ascending order in the matrix, and display the resultant matrix.

import java.io.*;
class SortColumns{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Number of rows: ");
        int m = Integer.parseInt(br.readLine());
        System.out.print("Number of columns: ");
        int n = Integer.parseInt(br.readLine());
        int a[][] = new int[m][n];
        System.out.println("Enter array elements:");
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                a[i][j] = Integer.parseInt(br.readLine());
            }
        }
        System.out.println("Original matrix:");
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                System.out.print(a[i][j] + "\t");
            }
            System.out.println();
        }
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                for(int k = 0; k < m - 1 - j; k++){ 
                    if(a[k][i] > a[k + 1][i]){
                        int temp = a[k][i];
                        a[k][i] = a[k + 1][i];
                        a[k + 1][i] = temp;
                    }
                }
            }
        }
        System.out.println("Sorted matrix:");
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                System.out.print(a[i][j] + "\t");
            }
            System.out.println();
        }
    }
}

Leave a Reply

%d bloggers like this: