Search This Blog

Monday 30 August 2021

2. Write a Java program to sort the elements of a square matrix. Read the order and elements of the matrix during execution. Before sorting the elements of the matrix, display the source matrix.

import java.io.*;
import java.util.*;
class  Program2
{
    public static void main(String[] args) throws IOException
    {
        int a[]=new int[100];
        int b[]=new int[100];
        int temp,num,i,j;
        System.out.println("Enter the order for square matrix:");
        DataInputStream in=new DataInputStream(System.in);
        int m=Integer.parseInt(in.readLine());
        System.out.println("Enter the elements:");
        for( i=0;i<(m*m);i++)
        {
                temp=Integer.parseInt(in.readLine());
                b[i]=temp;
                a[i]=temp;
            
        }
        System.out.println("The Source Matrix:\n");
        i=0;
        while(i<m*m)
        {
            for( j=0;j<m;j++)
            {
                System.out.print(a[i] + "\t");
                
                i++;
            }
                System.out.println();
        }

        for( i=0;i<m*m;i++)
        {
            for( j=i+1;j<=m*m;j++)
            {
                
                
                
                    if(a[i]>a[j])
                    {
                        temp=a[i];
                        a[i]=a[j];
                        a[j]=temp;
                    }
                
            }
        }
    
        System.out.println("The Sorted Matrix:\n");
        i=1;
        while(i<m*m)
        {
            for( j=0;j<m;j++)
            {
                System.out.print(a[i] + "\t");
                
                i++;
            }
                System.out.println();
        }
    }
}


No comments :

Post a Comment

FREE Hit Counters