Ordenar Matrix en orden ascendente y descendente alternado por filas

Dada una array N x N , nuestra tarea es imprimir la fila de la array en orden ascendente y descendente alternativamente.
Ejemplos: 

Entrada: 
5 7 3 4 
9 5 8 2 
6 3 8 1 
5 8 9 3 
Salida: 
3 4 5 7 
9 8 5 2 
1 3 6 8 
9 8 5 3 
Explicación: 
Aquí la primera fila está ordenada en orden ascendente, la segunda fila ordenados en orden descendente, la tercera fila ordenada en orden ascendente y así sucesivamente.
Entrada: 
7 3 4 
3 8 2 
3 6 1 
Salida: 
3 4 7 
8 3 2 
1 3 6 
Explicación: 
Aquí la primera fila se ordena en orden ascendente, la segunda fila en orden descendente, la tercera fila en orden ascendente. 

Enfoque para resolver
Para resolver el problema mencionado anteriormente, iteramos de 0 a N y verificamos si la i-ésima fila es par o impar , si es par, ordenamos la fila en orden ascendente; de ​​lo contrario, ordenamos la i-ésima fila en orden descendente. Devuelve la array después de N iteraciones.
A continuación se muestra la implementación del enfoque anterior:  

C++

// C++ implementation to print row of
// matrix in ascending or descending
// order alternatively
 
#include <stdio.h>
#define N 4
 
void func(int a[][N])
{
 
    // Iterate matrix rowwise
    for (int i = 0; i < N; i++) {
 
        // Sort even rows in ascending order
        if (i % 2 == 0) {
            for (int j = 0; j < N; j++) {
                for (int k = j + 1; k < N; ++k) {
 
                    // compare adjacent elements
                    if (a[i][j] > a[i][k]) {
 
                        // swap adjacent element
                        int temp = a[i][j];
                        a[i][j] = a[i][k];
                        a[i][k] = temp;
                    }
                }
            }
        }
 
        // Sort even rows in descending order
        else {
            for (int j = 0; j < N; j++) {
                for (int k = j + 1; k < N; ++k) {
 
                    // compare adjacent elements
                    if (a[i][j] < a[i][k]) {
 
                        // swap adjacent element
                        int temp = a[i][j];
                        a[i][j] = a[i][k];
                        a[i][k] = temp;
                    }
                }
            }
        }
    }
 
    // Printing the final Output
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            printf("%d ", a[i][j]);
        }
        printf("\n");
    }
}
 
// Driver code
int main()
{
 
    int a[N][N] = {
        { 5, 7, 3, 4 },
        { 9, 5, 8, 2 },
        { 6, 3, 8, 1 },
        { 5, 8, 9, 3 }
    };
 
    func(a);
 
    return 0;
}

Java

// Java implementation to print row of
// matrix in ascending or descending
// order alternatively
class GFG{
     
static int N = 4;
 
static void func(int a[][])
{
    int i, j, k;
     
    // Iterate matrix rowwise
    for(i = 0; i < N; i++)
    {
         
       // Sort even rows in ascending order
       if (i % 2 == 0)
       {
           for(j = 0; j < N; j++)
           {
              for(k = j + 1; k < N; ++k)
              {
                   
                 // Compare adjacent elements
                 if (a[i][j] > a[i][k])
                 {
                      
                     // Swap adjacent element
                     int temp = a[i][j];
                     a[i][j] = a[i][k];
                     a[i][k] = temp;
                 }
              }
           }
       }
        
       // Sort even rows in descending order
       else
       {
           for(j = 0; j < N; j++)
           {
              for(k = j + 1; k < N; ++k)
              {
                   
                 // Compare adjacent elements
                 if (a[i][j] < a[i][k])
                 {
                      
                     // Swap adjacent element
                     int temp = a[i][j];
                     a[i][j] = a[i][k];
                     a[i][k] = temp;
                 }
              }
           }
       }
    }
     
    // Printing the final Output
    for(i = 0; i < N; i++)
    {
       for(j = 0; j < N; j++)
       {
          System.out.print(a[i][j] + " ");
       }
       System.out.print("\n");
    }
}
 
// Driver code
public static void main (String []args)
{
 
    int a[][] = { { 5, 7, 3, 4 },
                  { 9, 5, 8, 2 },
                  { 6, 3, 8, 1 },
                  { 5, 8, 9, 3 } };
 
    func(a);
}
}
 
// This code is contributed by chitranayal

Python3

# Python3 implementation to print row of
# matrix in ascending or descending
# order alternatively
N = 4
 
def func(a):
     
    # Iterate matrix rowwise
    for i in range(N):
 
        # Sort even rows in ascending order
        if i % 2 == 0:
            for j in range(N):
                for k in range(j + 1, N):
                     
                    # Compare adjacent elements
                    if a[i][j] > a[i][k]:
                         
                        # Swap adjacent element
                        temp = a[i][j]
                        a[i][j] = a[i][k]
                        a[i][k] = temp
 
        # Sort even rows in descending order
        else :
            for j in range(N):
                for k in range(j + 1, N):
 
                    # Compare adjacent elements
                    if a[i][j] < a[i][k]:
 
                        # Swap adjacent element
                        temp = a[i][j]
                        a[i][j] = a[i][k]
                        a[i][k] = temp
 
    # Printing the final output
    for i in range(N):
        for j in range(N):
            print(a[i][j], end = " ")
        print()
         
# Driver code
if __name__ == '__main__':
 
    a = [ [ 5, 7, 3, 4 ],
          [ 9, 5, 8, 2 ],
          [ 6, 3, 8, 1 ],
          [ 5, 8, 9, 3 ] ]
           
    func(a)
 
# This code is contributed by mohit kumar 29

C#

// C# implementation to print row of
// matrix in ascending or descending
// order alternatively
using System;
class GFG{
     
static int N = 4;
 
static void func(int[,]a)
{
    int i, j, k;
     
    // Iterate matrix rowwise
    for(i = 0; i < N; i++)
    {
         
       // Sort even rows in ascending order
       if (i % 2 == 0)
       {
           for(j = 0; j < N; j++)
           {
              for(k = j + 1; k < N; ++k)
              {
                   
                 // Compare adjacent elements
                 if (a[i, j] > a[i, k])
                 {
                      
                     // Swap adjacent element
                     int temp = a[i, j];
                     a[i, j] = a[i, k];
                     a[i, k] = temp;
                 }
              }
           }
       }
        
       // Sort even rows in descending order
       else
       {
           for(j = 0; j < N; j++)
           {
              for(k = j + 1; k < N; ++k)
              {
                   
                 // Compare adjacent elements
                 if (a[i, j] < a[i, k])
                 {
                      
                     // Swap adjacent element
                     int temp = a[i, j];
                     a[i, j] = a[i, k];
                     a[i, k] = temp;
                 }
              }
           }
       }
    }
     
    // Printing the readonly Output
    for(i = 0; i < N; i++)
    {
       for(j = 0; j < N; j++)
       {
          Console.Write(a[i, j] + " ");
       }
       Console.Write("\n");
    }
}
 
// Driver code
public static void Main(String []args)
{
 
    int[,]a = { { 5, 7, 3, 4 },
                { 9, 5, 8, 2 },
                { 6, 3, 8, 1 },
                { 5, 8, 9, 3 } };
 
    func(a);
}
}
 
// This code is contributed by Princi Singh

Javascript

<script>
// Javascript implementation to print row of
// matrix in ascending or descending
// order alternatively
 
let N = 4;
 
function func(a)
{
 
    // Iterate matrix rowwise
    for (let i = 0; i < N; i++) {
 
        // Sort even rows in ascending order
        if (i % 2 == 0) {
            for (let j = 0; j < N; j++) {
                for (let k = j + 1; k < N; ++k) {
 
                    // compare adjacent elements
                    if (a[i][j] > a[i][k]) {
 
                        // swap adjacent element
                        let temp = a[i][j];
                        a[i][j] = a[i][k];
                        a[i][k] = temp;
                    }
                }
            }
        }
 
        // Sort even rows in descending order
        else {
            for (let j = 0; j < N; j++) {
                for (let k = j + 1; k < N; ++k) {
 
                    // compare adjacent elements
                    if (a[i][j] < a[i][k]) {
 
                        // swap adjacent element
                        let temp = a[i][j];
                        a[i][j] = a[i][k];
                        a[i][k] = temp;
                    }
                }
            }
        }
    }
 
    // Printing the final Output
    for (let i = 0; i < N; i++) {
        for (let j = 0; j < N; j++) {
            document.write(" " + a[i][j]);
        }
        document.write("<br>");
    }
}
 
// Driver code
 
    let a = [
        [ 5, 7, 3, 4 ],
        [ 9, 5, 8, 2 ],
        [ 6, 3, 8, 1 ],
        [ 5, 8, 9, 3 ]
    ];
 
    func(a);
 
// This code is contributed by subham348.
</script>
Producción: 

3 4 5 7 
9 8 5 2 
1 3 6 8 
9 8 5 3

 

Complejidad temporal: O(N 3 )

Espacio Auxiliar: O(1)

Enfoque eficiente: podemos optimizar el enfoque anterior ordenando cualquier fila usando la función sort() . Ordenará cualquier fila dada en complejidad de tiempo O (n * log (n)). 

Pasos involucrados en el enfoque:

  1. Recorra cada fila y verifique si la fila está en un número par o impar.
  2. Si hay filas pares, ordénelas en orden ascendente usando directamente la función de ordenación.
  3. Si la fila es impar, ordénela en orden descendente pasando la función «mayor()» en ordenación.

A continuación se muestra el código para el enfoque anterior:

C++

// C++ implementation to print row of
// matrix in ascending or descending
// order alternatively
 
#include <bits/stdc++.h>
using namespace std;
#define N 4
 
void func(int a[][N])
{
 
    // Iterate matrix rowwise
    for (int i = 0; i < N; i++) {
 
        // Sort even rows in ascending order
        if (i % 2 == 0) {
            sort(a[i],a[i]+N);
        }
 
        // Sort even rows in descending order
        else {
            sort(a[i],a[i]+N,greater<int>());
        }
    }
 
    // Printing the final Output
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            printf("%d ", a[i][j]);
        }
        printf("\n");
    }
}
 
// Driver code
int main()
{
 
    int a[N][N] = {
        { 5, 7, 3, 4 },
        { 9, 5, 8, 2 },
        { 6, 3, 8, 1 },
        { 5, 8, 9, 3 }
    };
 
    func(a);
 
    return 0;
}
 
// This code is contributed by Pushpesh Raj
Producción

3 4 5 7 
9 8 5 2 
1 3 6 8 
9 8 5 3 

Complejidad de tiempo: O(N 2 log(N))

Espacio Auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por arunkumar923gole 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 *