Sorting 2-D Array
In this Program we have to SORT a 2-D Matrix in ascending order.
Example :-
Algorithm and Program given Below :-
Algorithm :-
Step 1 : Input a 2-D Array (Square Matrix is preferred).
Step 2 : Store the 2-D Array elements in a 1-D Array.
Step 3 : Sort the 1-D Array elements.
Step 4 : Store the Sorted 1-D Array elements in new 2-D Array.
Program :-
import java.io.*; import java.util.*; class Sort { 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
Note : The program is written in the easiest way possible so try understand it. If you face any problem in understanding this program than feel free to contact/comment.
All the Best :)
Keep Learning :)
Commenti