How to fully sort 2d array in java?

Home / Uncategorized / How to fully sort 2d array in java?

Question:
I want to sort 2d array in java. For example Suppose I have this matrix
1 5 4
3 7 8
2 9 6

After sorting, result should be like
1 2 3
4 5 6
7 8 9

Please help me with this.

I have written following code for this problem
class Sort2dArrayFull{
public static void sort(int el[][]){
int m=0;
int n=0;
int temp=0;
int k1=1;

for(int i=0; iel[m+n][k1]){

temp=el[i][j];
el[i][j]=el[m+n][k1];
el[m+n][k1]=temp;

}

k1++;

if(k1==el[m+n].length){
k1=0;
}
if(k==el[m+n].length){
m++;

}

if(m==el.length){
m=0;
n++;
}

}
}
}

for(int i=0; i Answer:
If I were u, I’ll do as follows:public static void sort(int el[][]){
for(int i=0; i arrayToSort = new ArrayList();
for (int x = 0; x < el.length; x++) { for (int y = 0; y < el[x].length; y++) { arrayToSort.add(el[x][y]); } } Integer[] sortedArray = new Integer[arrayToSort.size()]; sortedArray = arrayToSort.toArray(sortedArray); Arrays.sort(sortedArray); int sequence = 0; for (int x = 0; x < el.length; x++) { for (int y = 0; y < el[x].length; y++) { el[x][y] = sortedArray[sequence++]; } } System.out.println("nAfter:"); for(int i=0; iRead more

Leave a Reply

Your email address will not be published. Required fields are marked *