Sort Matrix Rows Java Program | ISC Computer Science 2018 Practical

Write a program to declare a matrix A[][] of order (M × N) where ‘M’ is the number of rows and ‘N’ is the number of columns such that the values of both ‘M’ and ‘N’ must be greater than 2 and less than 10. Allow the user to input integers into this matrix.

Perform the following tasks on the matrix:
(a) Display the original matrix.
(b) Sort each row of the matrix in ascending order using any standard sorting technique.
(c) Display the changed matrix after sorting each row.

Test your program for the following data and some random data:

Example 1:
INPUT:
M = 4
N = 3
ENTER ELEMENTS OF MATRIX

11-23
5167
904
318

OUTPUT:
ORIGINAL MATRIX

11-23
5167
904
318

MATRIX AFTER SORTING ROWS

-2311
5716
049
138

Example 2:
INPUT:
M = 3
N = 3
ENTER ELEMENTS OF MATRIX

22519
73612
9136

OUTPUT:
ORIGINAL MATRIX

22519
73612
9136

MATRIX AFTER SORTING ROWS

51922
71236
6913

Example 3:
INPUT:
M = 11
N = 5
OUTPUT:
MATRIX SIZE OUT OF RANGE

import java.util.Scanner;
class Sort{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("M = ");
        int m = Integer.parseInt(in.nextLine());
        System.out.print("N = ");
        int n = Integer.parseInt(in.nextLine());
        if(m < 3 || m > 9 || n < 3 || n > 9){
            System.out.println("MATRIX SIZE OUT OF RANGE");
            return;
        }
        int a[][] = new int[m][n];
        System.out.println("ENTER ELEMENTS OF MATRIX");
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                a[i][j] = Integer.parseInt(in.nextLine());
            }
        }
        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 < m; i++){
            for(int j = 0; j < n; j++){
                for(int k = 0; k < n - 1 - j; k++){
                    if(a[i][k] > a[i][k + 1]){
                        int temp = a[i][k];
                        a[i][k] = a[i][k + 1];
                        a[i][k + 1] = temp;
                    }
                }
            }
        }
        System.out.println("MATRIX AFTER SORTING ROWS");
        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

Your email address will not be published. Required fields are marked *