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,845 questions

51,766 answers

573 users

How to search for a number in a sorted matrix in Scala

1 Answer

0 votes
object MatrixSearch {
  def searchMatrix(matrix: Array[Array[Int]], target: Int): Boolean = {
    val rows = matrix.length
    if (rows == 0) {
      println("Not found")
      return false
    }
    val cols = matrix(0).length

    var row = 0
    var col = cols - 1

    while (row < rows && col >= 0) {
      val value = matrix(row)(col)
      if (value == target) {
        println(s"Found: i = $row j = $col")
        return true
      } else if (value > target) {
        col -= 1
      } else {
        row += 1
      }
    }

    println("Not found")
    false
  }

  def main(args: Array[String]): Unit = {
    val matrix = Array(
      Array(2, 3, 5, 7, 8),
      Array(10, 13, 17, 18, 19),
      Array(25, 26, 30, 37, 38),
      Array(43, 46, 50, 51, 99)
    )

    searchMatrix(matrix, 37)
  }
}



/*
run:

Found: i = 2 j = 3

*/

 



answered Oct 8, 2025 by avibootz
...