Java 二次元配列のソート方法と出力例【サンプルコード付き】

Javaでは、2次元配列をソートするためにArraysクラスのsortメソッドを使用することができます。最初に、2次元配列を1次元配列に変換し、その後1次元配列をソートします。最後に、ソートされた1次元配列を再び2次元配列に変換します。

以下はサンプルコードです:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[][] arr = { { 5, 7, 1 }, { 8, 4, 6 }, { 3, 9, 2 } };

        int rows = arr.length;
        int cols = arr[0].length;

        int[] temp = new int[rows * cols];
        int index = 0;

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                temp[index++] = arr[i][j];
            }
        }

        Arrays.sort(temp);

        index = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                arr[i][j] = temp[index++];
            }
        }

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }
}

上記のコードを実行すると、ソートされた2次元配列が出力されます。

bannerAds