Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,788 questions

51,694 answers

573 users

How to sort each column of a matrix with strings in Java

1 Answer

0 votes
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
 
*/

 



answered Jun 2, 2025 by avibootz
...