Qns write a program in java to create an array A[][] of M*M.
1.display the original array
2.then sort the non boundary elements
3.print diagonal array
Eg
1 2 3 4
6 3 7 2
1 2 9 0
3 4 6 4
Output
1 2 3 4
6 2 3 2
1 7 9 0
3 4 6 4
Diagnol
1 4
23
79
3 4
The program for this problem is
import java.util.*;
class boundry
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("enter the dimenaions");
int M=in.nextInt();
int A[][]=new int[M][M];
int m=M*M-4*M+4;
int a[]=new int[m];//to collect non boundry elements
int x=0;
for(int i=0;i<M;i++)
{
for(int j=0;j<M;j++)
{
A[i][j]=in.nextInt();//storing elements in array
}
}
System.out.println("the original matrix");
for(int i=0;i<M;i++)
{
for(int j=0;j<M;j++)
System.out.print(" "+A[i][j]);
System.out.println();
}
for(int i=1;i<M-1;i++)
for(int j=1;j<M-1;j++)
a[x++]=A[i][j];
arraysort(a,m);// sortin the non boundry elements
x=0;
for(int i=1;i<M-1;i++)
for(int j=1;j<M-1;j++)
A[i][j]=a[x++];
System.out.println("the sorted matrix");
for(int i=0;i<M;i++)
{
for(int j=0;j<M;j++)
System.out.print(" "+A[i][j]);
System.out.println();
}
System.out.println("array in diagonal order");
x=4;
for(int i=0;i<M;i++)
{ --x;
for(int j=0;j<M;j++)
if((i==j)||(j==x))
System.out.print(" "+A[i][j]);
else
System.out.print(" "+" ");
System.out.println();
}
}
public static void arraysort(int []a,int j)
{
int min,swap=0;
for(int i=0;i<j;i++)
{
for(int k=0;k<j;k++)
{
if(a[i]<a[k])
{
swap=a[i];
a[i]=a[k];
a[k]=swap;
}}
}
}
}
No comments:
Post a Comment