Maximum and Minimum in a square matrix in C++


Problem statement

Given a square matrix of order n*n, find the maximum and minimum from the matrix

Example

If given matrix is −

{{15, 17, 19}, {5, 1, 7}, {14, 5, 16}}
then
Minimum number is 1 and maximum number is 19

Algorithm

  • Select two elements from the matrix one from the start of a row of the matrix another from the end of the same row of the matrix
  • Compare them and next compare smaller of them to the minimum of the matrix and larger of them to the maximum of the matrix.
  • We can see that for two elements we need 3 compare so for traversing whole of the matrix we need total of 3/2n2 comparisons

Example

Let us now see an example −

#include <bits/stdc++.h>
#define MAX 200
using namespace std;
void getMinMax(int matrix[MAX][MAX], int n) {
   int min = INT_MAX;
   int max = INT_MIN;
   for (int i = 0; i < n; ++i) {
      for (int j = 0; j <= n / 2; ++j){
         if (matrix[i][j] > matri[i][n - j - 1]) {
            if (min > matrixi][n - j - 1]) {
               min = marix[i][n - j -1];
            }
            if (max < matrixi][j]) {
               max = marix[i][j];
            }
         } else {
            if (min > matrixi][j]) {
               min = marix[i][j];
            }
            if (max < matrixi][n - j - 1]) {
               max = marix[i][n - j - 1];
            }
         }
      }
   }
   cout << "Maximum = " << max << ", Minimu = " << min << endl;
}
int main() {
   int matrix[MAX][MAX] = { {15, 17, 19}, {5, 1, 7}, {14, 5, 16} };
   getMinMax(matrix, 3);
   return 0;
}

Output

Maximum = 19, Minimum = 1

Updated on: 31-Dec-2019

126 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements