Сортировка двумерного массива с помощью Arrays.sort()
Возникла такая проблема. Нужно отсортировать массив по возрастанию с помощью метода Arrays.sort(). Например, есть такой массив: [3,8,5][1,6,7][2,4,9]
После сортировки должно вывести такое: [1,2,3][4,5,6][7,8,9]
Написал такой код, но он сортирует только по рядам:
package domain;
import java.util.Arrays;
/**
*
* @author Illia_R
*/
public class Exercise {
private int [][] matrix = {{34,2,15,12,56},
{3,67,6,21,9},
{22,5,18,65,10},
{52,36,112,90,0},
{19,48,73,16,88}};
public void DisplayArray() {
for (int[] row:matrix) {
System.out.println(Arrays.toString(row));
}
}
public void Sorting(){
for(int[] row:matrix) {
Arrays.sort(row);
}
}
}
UPD: Решил проблему вот так. Не знаю, правильно ли, но всё же может кому-то пригодиться:
package domain;
import java.util.Arrays;
/**
* A class that represents the exercise
* @author Illia_R
*/
public class Exercise {
private int N = 5;
private int counter = 0;
private int [][] matrix = {{34,2,15,12,56},
{3,67,6,21,9},
{22,5,18,65,10},
{52,36,112,90,0},
{19,48,73,16,88}};
private int [] flat = new int[N * N];
/**
* Method that displays the array
*/
public void DisplayArray() {
for (int[] row:matrix) {
System.out.println(Arrays.toString(row));
}
}
/**
* Method that sorts the array
*/
public void SortingArray() {
for(int row = 0; row < N; row++){
for(int col = 0; col < N; col++){
flat[counter++] = matrix[row][col];
}
}
Arrays.sort(flat);
counter = 0;
for (int row = 0; row < N; row++) {
for (int col = 0; col < N; col++) {
matrix[row][col] = flat[counter++];
}
}
}
}