Sort 2-D Array in Java
Sort 2-D Array in Java
In this Program we have to SORT a 2-D Matrix in ascending order.
Ex -
import java.io.*;
import java.util.*;
class Sort1
{
public static void main(String args[])
{
int n=0,t,i,j;
Scanner in= new Scanner(System.in);
int ar[][]=new int[3][3]; // Array Defined
int br[]=new int[9]; // 1-D Array to Store 2D array elements
int cr[][]=new int[3][3]; // 2D Array to store sorted data
System.out.println("Enter Array Elements");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
ar[i][j]= in.nextInt(); // Input Array Elements
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
br[n++]=ar[i][j]; // Storing 2D elements in 1D array
}
}
for(i=0;i<9;i++) // These two loops are used to Sort Array Elements of 1D Array
{
for(j=0;j<(8-i);j++)
{
if(br[j]>br[j+1])
{
t=br[j]; // Here 't' is a variable used for swapping
br[j]=br[j+1];
br[j+1]=t;
}
}
}
n=0; // This variable is used to increment the value of array position
for(i=0;i<3;i++) // Storing Sorted 1D array in New 2D Array
{
for(j=0;j<3;j++)
{
cr[i][j]=br[n++];
}
}
System.out.println("Original Matrix"); // Displaying original 2D Matrix
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(ar[i][j]+"\t");
}
System.out.println();
}
System.out.println("Sorted 2D Matrix"); // Displaying Sorted 2D Matrix
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(cr[i][j]+"\t");
}
System.out.println();
}
} // end of main
} // end of class
All the Best :)
Program :-
import java.util.*;
class Sort1
{
public static void main(String args[])
{
int n=0,t,i,j;
Scanner in= new Scanner(System.in);
int ar[][]=new int[3][3]; // Array Defined
int br[]=new int[9]; // 1-D Array to Store 2D array elements
int cr[][]=new int[3][3]; // 2D Array to store sorted data
System.out.println("Enter Array Elements");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
ar[i][j]= in.nextInt(); // Input Array Elements
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
br[n++]=ar[i][j]; // Storing 2D elements in 1D array
}
}
for(i=0;i<9;i++) // These two loops are used to Sort Array Elements of 1D Array
{
for(j=0;j<(8-i);j++)
{
if(br[j]>br[j+1])
{
t=br[j]; // Here 't' is a variable used for swapping
br[j]=br[j+1];
br[j+1]=t;
}
}
}
n=0; // This variable is used to increment the value of array position
for(i=0;i<3;i++) // Storing Sorted 1D array in New 2D Array
{
for(j=0;j<3;j++)
{
cr[i][j]=br[n++];
}
}
System.out.println("Original Matrix"); // Displaying original 2D Matrix
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(ar[i][j]+"\t");
}
System.out.println();
}
System.out.println("Sorted 2D Matrix"); // Displaying Sorted 2D Matrix
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(cr[i][j]+"\t");
}
System.out.println();
}
} // end of main
} // end of class
All the Best :)
Comments
Post a Comment