Máximo y Mínimo en una array cuadrada.

Dada una array cuadrada de orden n*n, encuentre el máximo y el mínimo de la array dada. 

Ejemplos: 

Input : arr[][] = {5, 4, 9,
                   2, 0, 6,
                   3, 1, 8};
Output : Maximum = 9, Minimum = 0

Input : arr[][] = {-5, 3, 
                   2, 4};
Output : Maximum = 4, Minimum = -5

Método ingenuo: 
encontramos el máximo y el mínimo de la array por separado mediante la búsqueda lineal. El número de comparación necesario es n 2 para encontrar el mínimo y n 2 para encontrar el elemento máximo. La comparación total es igual a 2n 2 .

Comparación de pares (método eficiente): 
seleccione dos elementos de la array, uno desde el comienzo de una fila de la array, otro desde el final de la misma fila de la array, compárelos y luego compare los más pequeños con el mínimo de la array y mayor de ellos al máximo de la array. Podemos ver que para dos elementos necesitamos 3 comparaciones, por lo que para recorrer toda la array necesitamos un total de 3/2 n 2 comparaciones.

Nota: Esta es una forma extendida del método 3 de Máximo Mínimo de Array.

Implementación:

C++

// C++ program for finding maximum and minimum in
// a matrix.
#include<bits/stdc++.h>
using namespace std;
 
#define MAX 100
 
// Finds maximum and minimum in arr[0..n-1][0..n-1]
// using pair wise comparisons
void maxMin(int arr[][MAX], int n)
{
    int min = INT_MAX;
    int max = INT_MIN;
 
    // Traverses rows one by one
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j <= n/2; j++)
        {
            // Compare elements from beginning
            // and end of current row
            if (arr[i][j] > arr[i][n-j-1])
            {
                if (min > arr[i][n-j-1])
                    min = arr[i][n-j-1];
                if (max< arr[i][j])
                    max = arr[i][j];
            }
            else
            {
                if (min > arr[i][j])
                    min = arr[i][j];
                if (max< arr[i][n-j-1])
                    max = arr[i][n-j-1];
            }
        }
    }
    cout << "Maximum = " << max
         << ", Minimum = " << min;
}
 
/* Driver program to test above function */
int main()
{
    int arr[MAX][MAX] = {5, 9, 11,
                        25, 0, 14,
                        21, 6, 4};
    maxMin(arr, 3);
    return 0;
}

Java

// Java program for finding maximum
// and minimum in a matrix.
 
class GFG
{
    static final int MAX = 100;
     
    // Finds maximum and minimum
    // in arr[0..n-1][0..n-1]
    // using pair wise comparisons
    static void maxMin(int arr[][], int n)
    {
        int min = +2147483647;
        int max = -2147483648;
     
        // Traverses rows one by one
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j <= n/2; j++)
            {
                // Compare elements from beginning
                // and end of current row
                if (arr[i][j] > arr[i][n - j - 1])
                {
                    if (min > arr[i][n - j - 1])
                        min = arr[i][n - j - 1];
                    if (max< arr[i][j])
                        max = arr[i][j];
                }
                else
                {
                    if (min > arr[i][j])
                        min = arr[i][j];
                    if (max< arr[i][n - j - 1])
                        max = arr[i][n - j - 1];
                }
            }
        }
        System.out.print("Maximum = "+max+
                         ", Minimum = "+min);
    }
     
    // Driver program
    public static void main (String[] args)
    {
        int arr[][] = {{5, 9, 11},
                       {25, 0, 14},
                       {21, 6, 4}};
        maxMin(arr, 3);
    }
}
 
// This code is contributed by Anant Agarwal.

Python3

# Python3 program for finding
# MAXimum and MINimum in a matrix.
MAX = 100
 
# Finds MAXimum and MINimum in arr[0..n-1][0..n-1]
# using pair wise comparisons
def MAXMIN(arr, n):
 
    MIN = 10**9
    MAX = -10**9
 
    # Traverses rows one by one
    for i in range(n):
        for j in range(n // 2 + 1):
             
        # Compare elements from beginning
        # and end of current row
            if (arr[i][j] > arr[i][n - j - 1]):
                if (MIN > arr[i][n - j - 1]):
                    MIN = arr[i][n - j - 1]
                if (MAX< arr[i][j]):
                    MAX = arr[i][j]
            else:
                if (MIN > arr[i][j]):
                    MIN = arr[i][j]
                if (MAX< arr[i][n - j - 1]):
                    MAX = arr[i][n - j - 1]
 
    print("MAXimum =", MAX, ", MINimum =", MIN)
 
# Driver Code
arr = [[5, 9, 11],
       [25, 0, 14],
       [21, 6, 4]]
 
MAXMIN(arr, 3)
 
# This code is contributed by Mohit Kumar

C#

// C# program for finding maximum
// and minimum in a matrix.
using System;
 
public class GFG {
     
    // Finds maximum and minimum
    // in arr[0..n-1][0..n-1]
    // using pair wise comparisons
    static void maxMin(int[,] arr, int n)
    {
        int min = +2147483647;
        int max = -2147483648;
     
        // Traverses rows one by one
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j <= n/2; j++)
            {
                 
                // Compare elements from beginning
                // and end of current row
                if (arr[i,j] > arr[i,n - j - 1])
                {
                    if (min > arr[i,n - j - 1])
                        min = arr[i,n - j - 1];
                    if (max < arr[i,j])
                        max = arr[i,j];
                }
                else
                {
                    if (min > arr[i,j])
                        min = arr[i,j];
                    if (max < arr[i,n - j - 1])
                        max = arr[i,n - j - 1];
                }
            }
        }
        Console.Write("Maximum = " + max +
                        ", Minimum = " + min);
    }
     
    // Driver code
    static public void Main ()
    {
        int[,] arr = { {5, 9, 11},
                       {25, 0, 14},
                       {21, 6, 4} };
                        
        maxMin(arr, 3);
    }
}
 
// This code is contributed by Shrikant13.

PHP

<?php
// PHP program for finding
// maximum and minimum in
// a matrix.
 
$MAX = 100;
 
// Finds maximum and minimum
// in arr[0..n-1][0..n-1]
// using pair wise comparisons
function maxMin($arr, $n)
{
    $min = PHP_INT_MAX;
    $max = PHP_INT_MIN;
 
    // Traverses rows one by one
    for ($i = 0; $i < $n; $i++)
    {
        for ($j = 0; $j <= $n / 2; $j++)
        {
             
            // Compare elements from beginning
            // and end of current row
            if ($arr[$i][$j] > $arr[$i][$n - $j - 1])
            {
                if ($min > $arr[$i][$n - $j - 1])
                    $min = $arr[$i][$n - $j - 1];
                if ($max< $arr[$i][$j])
                    $max = $arr[$i][$j];
            }
            else
            {
                if ($min > $arr[$i][$j])
                    $min = $arr[$i][$j];
                if ($max < $arr[$i][$n - $j - 1])
                    $max = $arr[$i][$n - $j - 1];
            }
        }
    }
    echo "Maximum = " , $max
        ,", Minimum = " , $min;
}
 
    // Driver Code
    $arr = array(array(5, 9, 11),
                array(25, 0, 14),
                array(21, 6, 4));
    maxMin($arr, 3);
     
// This code is contributed by anuj_67.
?>

Javascript

<script>
 
// Javascript program for finding maximum
// and minimum in a matrix.
let MAX = 100;
     
// Finds maximum and minimum
// in arr[0..n-1][0..n-1]
// using pair wise comparisons
function maxMin(arr,n)
{
    let min = +2147483647;
    let max = -2147483648;
 
    // Traverses rows one by one
    for(let i = 0; i < n; i++)
    {
        for(let j = 0; j <= n / 2; j++)
        {
             
            // Compare elements from beginning
            // and end of current row
            if (arr[i][j] > arr[i][n - j - 1])
            {
                if (min > arr[i][n - j - 1])
                    min = arr[i][n - j - 1];
                if (max< arr[i][j])
                    max = arr[i][j];
            }
            else
            {
                if (min > arr[i][j])
                    min = arr[i][j];
                if (max < arr[i][n - j - 1])
                    max = arr[i][n - j - 1];
            }
        }
    }
    document.write("Maximum = " + max +
                   ", Minimum = " + min);
}
 
// Driver Code
let arr = [ [ 5, 9, 11 ],
            [ 25, 0, 14 ],
            [ 21, 6, 4 ] ];
             
maxMin(arr, 3);
 
// This code is contributed by sravan kumar
 
</script>
Producción

Maximum = 11, Minimum = 0

Complejidad temporal: O(n 2 ).
Espacio Auxiliar: O(1)

Este artículo es una contribución de Aarti_Rathi y Shivam Pradhan (anuj_charm) . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks. 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *