Below is the code to sort principal diagonal in ascending order using Bubble sort technique.
import java.util.Scanner;
public class SortPrincipalDiagonal
{
public static void main(String[]args )
{
Scanner in=new Scanner(System.in);
System.out.println("Enter no. of rows for a square matrix: ");
int n=in.nextInt();
int a[][]=new int[n][n];
int i,j,k,t;
System.out.println("Enter the " +(n*n)+ " elements");
for(i=0;i < n;i++)// to input elemnts from user
{
for(j=0;j < n;j++)
{
a[i][j]=in.nextInt();
}
}
System.out.println("Original matrix: ");
for( i=0;i < n;i++)// to input elemnts from user
{
for( j=0;j < n;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
for( i=0;i < n;i++)// to input elemnts from user
{
for( j=1;j < n;j++)
{
for(k=0;k < n-j;k++){
if(a[k][k] > a[k+1][k+1]){
t = a[k][k];
a[k][k] = a[k+1][k+1];
a[k+1][k+1] = t;
}//if
} //loop k
} //loop j
}//loop i
System.out.println("Matrix after sorting prinicipal diagonal in ascending order: ");
for( i=0;i < n;i++)// to input elemnts from user
{
for( j=0;j < n;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
}
}
import java.util.Scanner;
public class SortPrincipalDiagonal
{
public static void main(String[]args )
{
Scanner in=new Scanner(System.in);
System.out.println("Enter no. of rows for a square matrix: ");
int n=in.nextInt();
int a[][]=new int[n][n];
int i,j,k,t;
System.out.println("Enter the " +(n*n)+ " elements");
for(i=0;i < n;i++)// to input elemnts from user
{
for(j=0;j < n;j++)
{
a[i][j]=in.nextInt();
}
}
System.out.println("Original matrix: ");
for( i=0;i < n;i++)// to input elemnts from user
{
for( j=0;j < n;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
for( i=0;i < n;i++)// to input elemnts from user
{
for( j=1;j < n;j++)
{
for(k=0;k < n-j;k++){
if(a[k][k] > a[k+1][k+1]){
t = a[k][k];
a[k][k] = a[k+1][k+1];
a[k+1][k+1] = t;
}//if
} //loop k
} //loop j
}//loop i
System.out.println("Matrix after sorting prinicipal diagonal in ascending order: ");
for( i=0;i < n;i++)// to input elemnts from user
{
for( j=0;j < n;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
}
}