
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- JavaScript Program for Maximum and Minimum in a Square Matrix
- Find Maximum side length of square in a Matrix in C++
- Print maximum sum square sub-matrix of given size in C Program.
- Finding the maximum square sub-matrix with all equal elements in C++
- Maximum and minimum isolated vertices in a graph in C++
- Maximum and Minimum Product Subsets in C++
- Maximum path sum in matrix in C++
- Maximum XOR value in matrix in C++
- Maximum and minimum of an array using minimum number of comparisons in C
- Minimum and Maximum Prime Numbers of a Singly Linked List in C++.
- Maximum decimal value path in a binary matrix in C++
- Find row with maximum sum in a Matrix in C++
- Product of maximum in first array and minimum in second in C
- How to read Maximum and Minimum temperature in Six's Maximum and Minimum Thermometer?
- How to multiply single row matrix and a square matrix in R?

Advertisements