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

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,705 questions

55,464 answers

573 users

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

1 Answer

0 votes
object MatrixColumnSorter {
  def sortColumns(matrix: Array[Array[String]]): Unit = {
    val rows = matrix.length
    val cols = matrix(0).length

    for (col <- 0 until cols) {
      // Extract column into an array
      val column = Array.ofDim[String](rows)
      for (row <- 0 until rows) {
        column(row) = matrix(row)(col)
      }

      // Sort the column
      scala.util.Sorting.quickSort(column)

      // Place sorted values back into the matrix
      for (row <- 0 until rows) {
        matrix(row)(col) = column(row)
      }
    }
  }

  def printMatrix(matrix: Array[Array[String]]): Unit = {
    matrix.foreach(row => println(row.mkString(" ")))
  }

  def main(args: Array[String]): Unit = {
    val matrix = Array(
      Array("ccc", "zzzz", "yyyyyy"),
      Array("eeee", "aaa", "ffff"),
      Array("uu", "hhh", "uuu"),
      Array("bbb", "gg", "x")
    )

    println("Original Matrix:")
    printMatrix(matrix)

    sortColumns(matrix)

    println("\nSorted Matrix:")
    printMatrix(matrix)
  }
}


 
/*
run:

Original Matrix:
ccc zzzz yyyyyy
eeee aaa ffff
uu hhh uuu
bbb gg x

Sorted Matrix:
bbb aaa ffff
ccc gg uuu
eeee hhh x
uu zzzz yyyyyy

*/

 



answered Jun 2, 2025 by avibootz
...