How to fully sort 2d array in java? -
i want sort 2d array in java. example suppose have matrix
1 5 4 3 7 8 2 9 6
after sorting, result should like
1 2 3 4 5 6 7 8 9
please me this.
i have written following code 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; i<el.length; i++){ for(int j=0; j<el[i].length; j++){ system.out.print(el[i][j]+" "); } system.out.print("\n"); } system.out.print("\n"); for(int i=0; i<el.length; i++){ for(int j=0; j<el[i].length; j++){ for(int k=j+1; k<el[m+n].length; k++){ if(el[i][j]>el[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<el.length; i++){ for(int j=0; j<el[i].length; j++){ system.out.print(el[i][j]+" "); } system.out.print("\n"); } } public static void main(string... args){ sort(new int[][]{{1,5,7,2},{55,44,11,77,33},{15,19,16,14,12,13}}); }
}
and output of program
//before sorting
1 5 7 2
55 44 11 77 33
15 19 16 14 12 13
//after sorting
19 15 44 55
1 7 5 77 33
2 11 16 14 12 13
but want result this
1 2 5 7
11 12 13 14 15
16 19 33 44 55 77
if u, i'll follows:
public static void sort(int el[][]){ for(int i=0; i<el.length; i++){ for(int j=0; j<el[i].length; j++){ system.out.print(el[i][j]+" "); } system.out.print("\n"); } arraylist<integer> arraytosort = new arraylist<integer>(); (int x = 0; x < el.length; x++) { (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; (int x = 0; x < el.length; x++) { (int y = 0; y < el[x].length; y++) { el[x][y] = sortedarray[sequence++]; } } system.out.println("\nafter:"); for(int i=0; i<el.length; i++){ for(int j=0; j<el[i].length; j++){ system.out.print(el[i][j]+" "); } system.out.print("\n"); } }
Comments
Post a Comment