OneCompiler

sort the matrix using insertion sort

165

Q5 Write a program to sort the matrix using insertion sort
object InsertionSortMatrix
{
def main(args: Array[String])
{
val matrix = Array(Array(5, 4, 7),
Array(1, 3, 8),
Array(2, 9, 6))

for (row <- 0 to 2)
{

  for (col <- 0 to 2) 
  {

    for (innerCol <- 0 until col) 
    {

      if (matrix(row)(innerCol) > matrix(row)(col))
      {
        val temp = matrix(row)(innerCol)
        matrix(row)(innerCol) = matrix(row)(col)
        matrix(row)(col) = temp
      }
    }
  }
}

println("Sorted Matrix :")
for (row <- 0 to 2) 
{
  for (col <- 0 to 2)
  {
    print(matrix(row)(col) + " ")
  }
  println()
}

}
}