Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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#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 matri[i][n - j - 1]) { if (min > matrixi][n - j - 1]) { min = marix[i][n - j -1]; } if (max matrixi][j]) { min = marix[i][j]; } if (max Output
Maximum = 19, Minimum = 1
Advertisements
