Posted on by Kalkicode
Code Matrix

Find the maximum and minimum element in a matrix

The problem at hand involves finding the maximum and minimum elements in a given matrix. A matrix is a two-dimensional array consisting of rows and columns. Each element in the matrix can be identified using its row and column indices.

Finding min max element in matrix

Problem Statement

Given a matrix with integer elements, we are required to find the maximum and minimum elements present in the matrix.

Example

Let's consider the following matrix as an example:

1  2  3  4  5
6 -7  8  9 10
11 12 13 15 16
17 18 19 28 21
22  8 24 25 26

In this matrix, the minimum element is -7, and the maximum element is 28.

Idea to Solve

To solve this problem, we can iterate through each element of the matrix and keep track of the minimum and maximum elements found so far.

Pseudocode

Here's the pseudocode to solve the problem:

function findMinMax(matrix):
    rows = number of rows in matrix
    cols = number of columns in matrix
    
    # Initialize min and max with the first element of the matrix
    min = matrix[0][0]
    max = min
    
    for i from 0 to rows-1:
        for j from 0 to cols-1:
            if matrix[i][j] < min:
                min = matrix[i][j]
            if matrix[i][j] > max:
                max = matrix[i][j]
    
    return min, max

Algorithm Explanation

  1. Get the number of rows and columns in the matrix.
  2. Initialize variables min and max with the value of the first element in the matrix.
  3. Iterate through each element of the matrix using nested loops.
  4. Compare the current element with the min value. If it's smaller, update the min.
  5. Compare the current element with the max value. If it's larger, update the max.
  6. After iterating through all elements, return the min and max values.

Code Solution

/*
   Java Program
   Find the maximum and minimum element in a matrix
*/
public class Test
{
    // Display matrix elements
    public void showData(int[][] matrix)
    {
        // Get the size of matrix
        int row = matrix.length;
        int col = matrix[0].length;
        // This loop is iterating rows
        for (int i = 0; i < row; ++i)
        {
            // This loop is iterating cols
            for (int j = 0; j < col; ++j)
            {
                // Display array element
                System.out.print("  " + matrix[i][j]);
            }
            // Include new line
            System.out.print("\n");
        }
        // Include new line
        System.out.print("\n");
    }
   
    public void minAndmax(int[][] matrix)
    {
        // Get the size of matrix
        int row = matrix.length;
        int col = matrix[0].length;

        // Assign first element into matrix
        int min = matrix[0][0];
        int max = min;
        // This loop is iterating rows
        for (int i = 0; i < row; ++i)
        {
            // This loop is iterating cols
            for (int j = 0; j < col; ++j)
            {
                if (min > matrix[i][j])
                {
                    // Get new min value
                    min = matrix[i][j];
                }
                if (max < matrix[i][j])
                {
                    // Get new max value
                    max = matrix[i][j];
                }
            }
        }
        // Display result
        System.out.println("  Min : " + min);
        System.out.println("  Max : " + max );
    }
    public static void main(String[] args)
    {
        Test task = new Test();
        // Define matrix 
        int[][] matrix =  {
            {
                1 , 2 , 3 , 4 , 5
            } , {
                6 , -7 , 8 , 9 , 10
            } , {
                11 , 12 , 13 , 15 , 16
            } , {
                17 , 18 , 19 , 28 , 21
            } , {
                22 , 8 , 24 , 25 , 26
            }
        };
        task.showData(matrix);
        task.minAndmax(matrix);
    }
}

Output

  1  2  3  4  5
  6  -7  8  9  10
  11  12  13  15  16
  17  18  19  28  21
  22  8  24  25  26

  Min : -7
  Max : 28
package main
import "fmt"
/*
   Go Program
   Find the maximum and minimum element in a matrix
*/
type Test struct {}
func getTest() * Test {
  var me *Test = &Test {}
  return me
}
// Display matrix elements
func(this Test) showData(matrix[][] int) {
  // Get the size of matrix
  var row int = len(matrix)
  var col int = len(matrix[0])
  // This loop is iterating rows
  for i := 0 ; i < row ; i++ {
    // This loop is iterating cols
    for j := 0 ; j < col ; j++ {
      // Display array element
      fmt.Print("  ", matrix[i][j])
    }
    // Include new line
    fmt.Print("\n")
  }
  // Include new line
  fmt.Print("\n")
}
func(this Test) minAndmax(matrix[][] int) {
  // Get the size of matrix
  var row int = len(matrix)
  var col int = len(matrix[0])
  // Assign first element into matrix
  var min int = matrix[0][0]
  var max int = min
  // This loop is iterating rows
  for i := 0 ; i < row ; i++ {
    // This loop is iterating cols
    for j := 0 ; j < col ; j++ {
      if min > matrix[i][j] {
        // Get new min value
        min = matrix[i][j]
      }
      if max < matrix[i][j] {
        // Get new max value
        max = matrix[i][j]
      }
    }
  }
  // Display result
  fmt.Println("  Min : ", min)
  fmt.Println("  Max : ", max)
}
func main() {
  var task * Test = getTest()
  // Define matrix 
  var matrix = [][] int {
    { 1 , 2 , 3 , 4 , 5 }, 
    { 6 , -7 , 8 , 9 , 10 } , 
    { 11 , 12 , 13 , 15 , 16} , 
    { 17 , 18 , 19 , 28 , 21} , 
    { 22 , 8 , 24 , 25 , 26 },
  }
  task.showData(matrix)
  task.minAndmax(matrix)
}

Output

  1  2  3  4  5
  6  -7  8  9  10
  11  12  13  15  16
  17  18  19  28  21
  22  8  24  25  26

  Min : -7
  Max : 28
// Include header file
#include <iostream>
#include <vector>

using namespace std;
/*
   C++ Program
   Find the maximum and minimum element in a matrix
*/
class Test
{
  public:
    // Display matrix elements
    void showData(vector < vector < int >> matrix)
    {
      // Get the size of matrix
      int row = matrix.size();
      int col = matrix[0].size();
      // This loop is iterating rows
      for (int i = 0; i < row; ++i)
      {
        // This loop is iterating cols
        for (int j = 0; j < col; ++j)
        {
          // Display array element
          cout << "  " << matrix[i][j];
        }
        // Include new line
        cout << "\n";
      }
      // Include new line
      cout << "\n";
    }
  void minAndmax(vector < vector < int >> matrix)
  {
    // Get the size of matrix
    int row = matrix.size();
    int col = matrix[0].size();
    // Assign first element into matrix
    int min = matrix[0][0];
    int max = min;
    // This loop is iterating rows
    for (int i = 0; i < row; ++i)
    {
      // This loop is iterating cols
      for (int j = 0; j < col; ++j)
      {
        if (min > matrix[i][j])
        {
          // Get new min value
          min = matrix[i][j];
        }
        if (max < matrix[i][j])
        {
          // Get new max value
          max = matrix[i][j];
        }
      }
    }
    // Display result
    cout << "  Min : " << min << endl;
    cout << "  Max : " << max << endl;
  }
};
int main()
{
  Test *task = new Test();
  // Matrix of integer elements
  vector < vector < int >> matrix
  {
    {1 , 2 , 3 , 4 , 5}, 
        {6 , -7 , 8 , 9 , 10}, 
        {11 , 12 , 13 , 15 , 16}, 
        {17 , 18 , 19 , 28 , 21}, 
        {22 , 8 , 24 , 25 , 26}
  };
  task->showData(matrix);
  task->minAndmax(matrix);
  return 0;
}

Output

  1  2  3  4  5
  6  -7  8  9  10
  11  12  13  15  16
  17  18  19  28  21
  22  8  24  25  26

  Min : -7
  Max : 28
/*
  C Program 
  Find the maximum and minimum element in a matrix
*/
#include<stdio.h>
#define ROW 5
#define COL 5

// Display matrix element
void show_data(int matrix[][COL])
{
    // This loop is iterating rows
  for (int i = 0; i < ROW; ++i)
  {
        // This loop is iterating cols
    for (int j = 0; j < COL; ++j)
    {  
            // Display element
      printf("%3d", matrix[i][j]);
    }
        // Include new line
    printf("\n");
  }
    // Include new line
  printf("\n");
}
void min_max(int matrix[ROW][COL])
{
  // Assign first element into matrix
  int min = matrix[0][0];
  int max = min;
     // This loop is iterating rows
  for (int i = 0; i < ROW; ++i)
  {
        // This loop is iterating cols
    for (int j = 0; j < COL; ++j)
    {
      if (min > matrix[i][j])
      {
                // Get new min value
        min = matrix[i][j];
      }
      if (max < matrix[i][j])
      {
                // Get new max value
        max = matrix[i][j];
      }
    }
  }
    // Display result
  printf("Min : %d\n", min);
  printf("Max : %d\n", max);
}
int main()
{
  int matrix[ROW][COL] = {
    {
      1 , 2 , 3 , 4 , 5
    },
    {
      6 , -7 , 8 , 9 , 10
    },
    {
      11 , 12 , 13 , 15 , 16
    },
    {
      17 , 18 , 19 , 28 , 21
    },
    {
      22 , 8 , 24 , 25 , 26
    }
  };
  show_data(matrix);
  min_max(matrix);
  return 0;
}

Output

  1  2  3  4  5
  6 -7  8  9 10
 11 12 13 15 16
 17 18 19 28 21
 22  8 24 25 26

Min : -7
Max : 28
// Include namespace system
using System;
/*
   Csharp Program
   Find the maximum and minimum element in a matrix
*/
public class Test
{
  // Display matrix elements
  public void showData(int[,] matrix)
  {
    // Get the size of matrix
    int row = matrix.GetLength(0);
    int col = matrix.GetLength(1);
    // This loop is iterating rows
    for (int i = 0; i < row; ++i)
    {
      // This loop is iterating cols
      for (int j = 0; j < col; ++j)
      {
        // Display array element
        Console.Write("  " + matrix[i,j]);
      }
      // Include new line
      Console.Write("\n");
    }
    // Include new line
    Console.Write("\n");
  }
  public void minAndmax(int[,] matrix)
  {
    // Get the size of matrix
    int row = matrix.GetLength(0);
    int col = matrix.GetLength(1);
    // Assign first element into matrix
    int min = matrix[0,0];
    int max = min;
    // This loop is iterating rows
    for (int i = 0; i < row; ++i)
    {
      // This loop is iterating cols
      for (int j = 0; j < col; ++j)
      {
        if (min > matrix[i,j])
        {
          // Get new min value
          min = matrix[i,j];
        }
        if (max < matrix[i,j])
        {
          // Get new max value
          max = matrix[i,j];
        }
      }
    }
    // Display result
    Console.WriteLine("  Min : " + min);
    Console.WriteLine("  Max : " + max);
  }
  public static void Main(String[] args)
  {
    Test task = new Test();
    // Define matrix 
    int[,] matrix = {
      {
        1 , 2 , 3 , 4 , 5
      },
      {
        6 , -7 , 8 , 9 , 10
      },
      {
        11 , 12 , 13 , 15 , 16
      },
      {
        17 , 18 , 19 , 28 , 21
      },
      {
        22 , 8 , 24 , 25 , 26
      }
    };
    task.showData(matrix);
    task.minAndmax(matrix);
  }
}

Output

  1  2  3  4  5
  6  -7  8  9  10
  11  12  13  15  16
  17  18  19  28  21
  22  8  24  25  26

  Min : -7
  Max : 28
<?php
/*
   Php Program
   Find the maximum and minimum element in a matrix
*/
class Test
{
  // Display matrix elements
  public  function showData($matrix)
  {
    // Get the size of matrix
    $row = count($matrix);
    $col = count($matrix[0]);
    // This loop is iterating rows
    for ($i = 0; $i < $row; ++$i)
    {
      // This loop is iterating cols
      for ($j = 0; $j < $col; ++$j)
      {
        // Display array element
        echo("  ".$matrix[$i][$j]);
      }
      // Include new line
      echo("\n");
    }
    // Include new line
    echo("\n");
  }
  public  function minAndmax($matrix)
  {
    // Get the size of matrix
    $row = count($matrix);
    $col = count($matrix[0]);
    // Assign first element into matrix
    $min = $matrix[0][0];
    $max = $min;
    // This loop is iterating rows
    for ($i = 0; $i < $row; ++$i)
    {
      // This loop is iterating cols
      for ($j = 0; $j < $col; ++$j)
      {
        if ($min > $matrix[$i][$j])
        {
          // Get new min value
          $min = $matrix[$i][$j];
        }
        if ($max < $matrix[$i][$j])
        {
          // Get new max value
          $max = $matrix[$i][$j];
        }
      }
    }
    // Display result
    echo("  Min : ".$min.
      "\n");
    echo("  Max : ".$max.
      "\n");
  }
}

function main()
{
  $task = new Test();
  // Define matrix 
  $matrix = array(
      array(1, 2, 3, 4, 5), 
      array(6, -7, 8, 9, 10), 
      array(11, 12, 13, 15, 16), 
      array(17, 18, 19, 28, 21), 
      array(22, 8, 24, 25, 26)
    );
  $task->showData($matrix);
  $task->minAndmax($matrix);
}
main();

Output

  1  2  3  4  5
  6  -7  8  9  10
  11  12  13  15  16
  17  18  19  28  21
  22  8  24  25  26

  Min : -7
  Max : 28
/*
   Node JS Program
   Find the maximum and minimum element in a matrix
*/
class Test
{
  // Display matrix elements
  showData(matrix)
  {
    // Get the size of matrix
    var row = matrix.length;
    var col = matrix[0].length;
    // This loop is iterating rows
    for (var i = 0; i < row; ++i)
    {
      // This loop is iterating cols
      for (var j = 0; j < col; ++j)
      {
        // Display array element
        process.stdout.write("  " + matrix[i][j]);
      }
      // Include new line
      process.stdout.write("\n");
    }
    // Include new line
    process.stdout.write("\n");
  }
  minAndmax(matrix)
  {
    // Get the size of matrix
    var row = matrix.length;
    var col = matrix[0].length;
    // Assign first element into matrix
    var min = matrix[0][0];
    var max = min;
    // This loop is iterating rows
    for (var i = 0; i < row; ++i)
    {
      // This loop is iterating cols
      for (var j = 0; j < col; ++j)
      {
        if (min > matrix[i][j])
        {
          // Get new min value
          min = matrix[i][j];
        }
        if (max < matrix[i][j])
        {
          // Get new max value
          max = matrix[i][j];
        }
      }
    }
    // Display result
    console.log("  Min : " + min);
    console.log("  Max : " + max);
  }
}

function main()
{
  var task = new Test();
  // Define matrix 
  var matrix = [
    [1, 2, 3, 4, 5],
    [6, -7, 8, 9, 10],
    [11, 12, 13, 15, 16],
    [17, 18, 19, 28, 21],
    [22, 8, 24, 25, 26]
  ];
  task.showData(matrix);
  task.minAndmax(matrix);
}
main();

Output

  1  2  3  4  5
  6  -7  8  9  10
  11  12  13  15  16
  17  18  19  28  21
  22  8  24  25  26

  Min : -7
  Max : 28
#   Python 3 Program
#   Find the maximum and minimum element in a matrix
class Test :
  #  Display matrix elements
  def showData(self, matrix) :
    #  Get the size of matrix
    row = len(matrix)
    col = len(matrix[0])
    i = 0
    #  This loop is iterating rows
    while (i < row) :
      j = 0
      #  This loop is iterating cols
      while (j < col) :
        #  Display list element
        print("  ", matrix[i][j], end = "")
        j += 1
      
      #  Include new line
      print(end = "\n")
      i += 1
    
    #  Include new line
    print(end = "\n")
  
  def minAndmax(self, matrix) :
    #  Get the size of matrix
    row = len(matrix)
    col = len(matrix[0])
    #  Assign first element into matrix
    min = matrix[0][0]
    max = min
    i = 0
    #  This loop is iterating rows
    while (i < row) :
      j = 0
      #  This loop is iterating cols
      while (j < col) :
        if (min > matrix[i][j]) :
          #  Get new min value
          min = matrix[i][j]
        
        if (max < matrix[i][j]) :
          #  Get new max value
          max = matrix[i][j]
        
        j += 1
      
      i += 1
    
    #  Display result
    print("  Min : ", min)
    print("  Max : ", max)
  

def main() :
  task = Test()
  #  Define matrix 
  matrix = [
    [1, 2, 3, 4, 5],
    [6, -7, 8, 9, 10],
    [11, 12, 13, 15, 16],
    [17, 18, 19, 28, 21],
    [22, 8, 24, 25, 26]
  ]
  task.showData(matrix)
  task.minAndmax(matrix)

if __name__ == "__main__": main()

Output

   1   2   3   4   5
   6   -7   8   9   10
   11   12   13   15   16
   17   18   19   28   21
   22   8   24   25   26

  Min :  -7
  Max :  28
#   Ruby Program
#   Find the maximum and minimum element in a matrix
class Test 
  #  Display matrix elements
  def showData(matrix) 
    #  Get the size of matrix
    row = matrix.length
    col = matrix[0].length
    i = 0
    #  This loop is iterating rows
    while (i < row) 
      j = 0
      #  This loop is iterating cols
      while (j < col) 
        #  Display array element
        print("  ", matrix[i][j])
        j += 1
      end

      #  Include new line
      print("\n")
      i += 1
    end

    #  Include new line
    print("\n")
  end

  def minAndmax(matrix) 
    #  Get the size of matrix
    row = matrix.length
    col = matrix[0].length
    #  Assign first element into matrix
    min = matrix[0][0]
    max = min
    i = 0
    #  This loop is iterating rows
    while (i < row) 
      j = 0
      #  This loop is iterating cols
      while (j < col) 
        if (min > matrix[i][j]) 
          #  Get new min value
          min = matrix[i][j]
        end

        if (max < matrix[i][j]) 
          #  Get new max value
          max = matrix[i][j]
        end

        j += 1
      end

      i += 1
    end

    #  Display result
    print("  Min : ", min, "\n")
    print("  Max : ", max, "\n")
  end

end

def main() 
  task = Test.new()
  #  Define matrix 
  matrix = [
    [1, 2, 3, 4, 5],
    [6, -7, 8, 9, 10],
    [11, 12, 13, 15, 16],
    [17, 18, 19, 28, 21],
    [22, 8, 24, 25, 26]
  ]
  task.showData(matrix)
  task.minAndmax(matrix)
end

main()

Output

  1  2  3  4  5
  6  -7  8  9  10
  11  12  13  15  16
  17  18  19  28  21
  22  8  24  25  26

  Min : -7
  Max : 28
/*
   Scala Program
   Find the maximum and minimum element in a matrix
*/
class Test()
{
  // Display matrix elements
  def showData(matrix: Array[Array[Int]]): Unit = {
    // Get the size of matrix
    var row: Int = matrix.length;
    var col: Int = matrix(0).length;
    var i: Int = 0;
    // This loop is iterating rows
    while (i < row)
    {
      var j: Int = 0;
      // This loop is iterating cols
      while (j < col)
      {
        // Display array element
        print("  " + matrix(i)(j));
        j += 1;
      }
      // Include new line
      print("\n");
      i += 1;
    }
    // Include new line
    print("\n");
  }
  def minAndmax(matrix: Array[Array[Int]]): Unit = {
    // Get the size of matrix
    var row: Int = matrix.length;
    var col: Int = matrix(0).length;
    // Assign first element into matrix
    var min: Int = matrix(0)(0);
    var max: Int = min;
    var i: Int = 0;
    // This loop is iterating rows
    while (i < row)
    {
      var j: Int = 0;
      // This loop is iterating cols
      while (j < col)
      {
        if (min > matrix(i)(j))
        {
          // Get new min value
          min = matrix(i)(j);
        }
        if (max < matrix(i)(j))
        {
          // Get new max value
          max = matrix(i)(j);
        }
        j += 1;
      }
      i += 1;
    }
    // Display result
    println("  Min : " + min);
    println("  Max : " + max);
  }
}
object Main
{
  def main(args: Array[String]): Unit = {
    var task: Test = new Test();
    // Define matrix 
    var matrix: Array[Array[Int]] = Array(
          Array(1, 2, 3, 4, 5), 
          Array(6, -7, 8, 9, 10), 
          Array(11, 12, 13, 15, 16), 
          Array(17, 18, 19, 28, 21), 
          Array(22, 8, 24, 25, 26)
        );
    task.showData(matrix);
    task.minAndmax(matrix);
  }
}

Output

  1  2  3  4  5
  6  -7  8  9  10
  11  12  13  15  16
  17  18  19  28  21
  22  8  24  25  26

  Min : -7
  Max : 28
import Foundation;
/*
   Swift 4 Program
   Find the maximum and minimum element in a matrix
*/
class Test
{
  // Display matrix elements
  func showData(_ matrix: [[Int]])
  {
    // Get the size of matrix
    let row: Int = matrix.count;
    let col: Int = matrix[0].count;
    var i: Int = 0;
    // This loop is iterating rows
    while (i < row)
    {
      var j: Int = 0;
      // This loop is iterating cols
      while (j < col)
      {
        // Display array element
        print("  ", matrix[i][j], terminator: "");
        j += 1;
      }
      // Include new line
      print(terminator: "\n");
      i += 1;
    }
    // Include new line
    print(terminator: "\n");
  }
  func minAndmax(_ matrix: [
    [Int]
  ])
  {
    // Get the size of matrix
    let row: Int = matrix.count;
    let col: Int = matrix[0].count;
    // Assign first element into matrix
    var min: Int = matrix[0][0];
    var max: Int = min;
    var i: Int = 0;
    // This loop is iterating rows
    while (i < row)
    {
      var j: Int = 0;
      // This loop is iterating cols
      while (j < col)
      {
        if (min > matrix[i][j])
        {
          // Get new min value
          min = matrix[i][j];
        }
        if (max < matrix[i][j])
        {
          // Get new max value
          max = matrix[i][j];
        }
        j += 1;
      }
      i += 1;
    }
    // Display result
    print("  Min : ", min);
    print("  Max : ", max);
  }
}
func main()
{
  let task: Test = Test();
  // Define matrix 
  let matrix: [[Int]] = [
    [1, 2, 3, 4, 5],
    [6, -7, 8, 9, 10],
    [11, 12, 13, 15, 16],
    [17, 18, 19, 28, 21],
    [22, 8, 24, 25, 26]
  ];
  task.showData(matrix);
  task.minAndmax(matrix);
}
main();

Output

   1   2   3   4   5
   6   -7   8   9   10
   11   12   13   15   16
   17   18   19   28   21
   22   8   24   25   26

  Min :  -7
  Max :  28
/*
   Kotlin Program
   Find the maximum and minimum element in a matrix
*/
class Test
{
  // Display matrix elements
  fun showData(matrix: Array < Array < Int >> ): Unit
  {
    // Get the size of matrix
    val row: Int = matrix.count();
    val col: Int = matrix[0].count();
    var i: Int = 0;
    // This loop is iterating rows
    while (i < row)
    {
      var j: Int = 0;
      // This loop is iterating cols
      while (j < col)
      {
        // Display array element
        print("  " + matrix[i][j]);
        j += 1;
      }
      // Include new line
      print("\n");
      i += 1;
    }
    // Include new line
    print("\n");
  }
  fun minAndmax(matrix: Array < Array < Int >> ): Unit
  {
    // Get the size of matrix
    val row: Int = matrix.count();
    val col: Int = matrix[0].count();
    // Assign first element into matrix
    var min: Int = matrix[0][0];
    var max: Int = min;
    var i: Int = 0;
    // This loop is iterating rows
    while (i < row)
    {
      var j: Int = 0;
      // This loop is iterating cols
      while (j < col)
      {
        if (min > matrix[i][j])
        {
          // Get new min value
          min = matrix[i][j];
        }
        if (max < matrix[i][j])
        {
          // Get new max value
          max = matrix[i][j];
        }
        j += 1;
      }
      i += 1;
    }
    // Display result
    println("  Min : " + min);
    println("  Max : " + max);
  }
}
fun main(args: Array < String > ): Unit
{
  val task: Test = Test();
  // Define matrix 
  val matrix: Array < Array < Int >> = arrayOf(
      arrayOf(1, 2, 3, 4, 5), 
      arrayOf(6, -7, 8, 9, 10), 
      arrayOf(11, 12, 13, 15, 16), 
      arrayOf(17, 18, 19, 28, 21), 
      arrayOf(22, 8, 24, 25, 26)
    );
  task.showData(matrix);
  task.minAndmax(matrix);
}

Output

  1  2  3  4  5
  6  -7  8  9  10
  11  12  13  15  16
  17  18  19  28  21
  22  8  24  25  26

  Min : -7
  Max : 28

Time Complexity Analysis

The algorithm iterates through all elements of the matrix exactly once, leading to a time complexity of O(rows * cols), where rows and cols are the dimensions of the matrix.

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment