import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class MatrixColumnSorter {
public static void sortColumns(String[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
for (int col = 0; col < cols; col++) {
// Extract column into a list
List<String> column = Arrays.asList(new String[rows]);
for (int row = 0; row < rows; row++) {
column.set(row, matrix[row][col]);
}
// Sort the column
Collections.sort(column);
// Place sorted values back into the matrix
for (int row = 0; row < rows; row++) {
matrix[row][col] = column.get(row);
}
}
}
public static void printMatrix(String[][] matrix) {
for (String[] row : matrix) {
System.out.println(String.join(" ", row));
}
}
public static void main(String[] args) {
String[][] matrix = {
{"ccc", "zzzz", "x"},
{"eeee", "aaa", "ffff"},
{"uu", "hhh", "uuu"},
{"bbb", "gg", "yyyyyy"}
};
System.out.println("Original Matrix:");
printMatrix(matrix);
sortColumns(matrix);
System.out.println("\nSorted Matrix:");
printMatrix(matrix);
}
}
/*
run:
Original Matrix:
ccc zzzz x
eeee aaa ffff
uu hhh uuu
bbb gg yyyyyy
Sorted Matrix:
bbb aaa ffff
ccc gg uuu
eeee hhh x
uu zzzz yyyyyy
*/