Skip to main content

Program in java to accept a 3x3 matrix. Sort the matrix is ascending order using selection sort

 WAP to accept a 3x3 matrix. Sort the matrix is ascending order using selection sort.

Input:
7 1 5
4 3 2
2 9 6
Output:
1 2 2
3 4 5
6 7 9
Process:
1) Convert the 2D in 1D array
2) Apply selection on 1D array
3) Reconvert 1D to 2D array


import java.util.Scanner;
class ArraySort
{
int A[][],m,n; //m and n are rows and columns
ArraySort(int m,int n)
{
this.m=m;
this.n=n;
A = new int[m][n];
}
void accept()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the values into the matrix:");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
A[i][j]=sc.nextInt();
}
}
}
void display()
{
//1D Array
int B[] = new int[m*n];
int c=0;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
B[c++]=A[i][j];
}
}
//Selection Sort
int k = B.length;
for(int i=0;i<k-1;i++)
{
int min = i;
for(int j=i+1;j<k;j++)
{
if(B[min]>B[j])
{
min=j;
}
}
int t = B[min];
B[min]=B[i];
B[i]=t;
}
//1D to 2D
c=0;
int C[][] = new int[m][n];
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
C[i][j]=B[c++];
}
}
//Now the moment of truth
System.out.println("Sorted array:");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(C[i][j]+" ");
}
System.out.println();
}
}
public static void main(String args[])
{
ArraySort ob = new ArraySort(3,3);
ob.accept();
ob.display();
}
}

Popular posts from this blog