Imprimir elementos de array en orden creciente y decreciente alternativamente

Dada una array de N elementos. La tarea es imprimir los elementos de la array de tal manera que los primeros dos elementos estén en orden creciente, los siguientes 3 en orden decreciente, los siguientes 4 en orden creciente y así sucesivamente.

Ejemplos

Entrada : arr = {2, 6, 2, 4, 0, 1, 4, 8, 2, 0, 0, 5,2,2} Salida: 0 
0 8 6 5 0 1 2 2 4 4 2 2 2 

Entrada : arr = {1, 2, 3, 4, 5, 6} 
Salida : 1 2 6 5 4 3 
 
 

Fuente : Oracle Interview experience set 52
La idea es utilizar la técnica de 2 punteros . Primero ordene la array en orden creciente y mantenga dos punteros  l    r    donde  l    es para imprimir la array en orden creciente y  r    para imprimir la array en orden decreciente. Mantenga una variable  K    para especificar el número de elementos que se imprimirán en una iteración y un indicador de variable para cambiar entre la impresión en orden creciente y decreciente alternativamente.

A continuación se muestra la implementación del enfoque anterior:  

C++

// C++ program to print array elements in
// alternative increasing and decreasing
// order
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to print array elements in
// alternative increasing and decreasing
// order
void printArray(int arr[], int n)
{
    // First sort the array in increasing order
    sort(arr, arr + n);
 
    int l = 0, r = n - 1, flag = 0, i;
 
    // start with 2 elements in
    // increasing order
    int k = 2;
 
    // till all the elements are not printed
    while (l <= r) {
        // printing the elements in
        // increasing order
        if (flag == 0) {
            for (i = l; i < l + k && i <= r; i++)
                cout << arr[i] << " ";
 
            flag = 1;
            l = i;
        }
        else // printing the elements in
        // decreasing order
        {
            for (i = r; i > r - k && i >= l; i--)
                cout << arr[i] << " ";
 
            flag = 0;
            r = i;
        }
 
        // increasing the number of elements
        // to printed in next iteration
        k++;
    }
}
 
// Driver Code
int main()
{
    int n = 6;
 
    int arr[] = { 1, 2, 3, 4, 5, 6 };
 
    printArray(arr, n);
 
    return 0;
}

Java

// Java program to print array elements in
// alternative increasing and decreasing
// order
import java.util.*;
class Solution
{
  
// Function to print array elements in
// alternative increasing and decreasing
// order
static void printArray(int arr[], int n)
{
    // First sort the array in increasing order
    Arrays.sort(arr);
  
    int l = 0, r = n - 1, flag = 0, i;
  
    // start with 2 elements in
    // increasing order
    int k = 2;
  
    // till all the elements are not printed
    while (l <= r) {
        // printing the elements in
        // increasing order
        if (flag == 0) {
            for (i = l; i < l + k && i <= r; i++)
                System.out.print(arr[i] + " ");
  
            flag = 1;
            l = i;
        }
        else // printing the elements in
        // decreasing order
        {
            for (i = r; i > r - k && i >= l; i--)
                System.out.print(arr[i] + " ");
  
            flag = 0;
            r = i;
        }
  
        // increasing the number of elements
        // to printed in next iteration
        k++;
    }
}
  
// Driver Code
public static void main(String args[])
{
    int n = 6;
  
    int arr[] = { 1, 2, 3, 4, 5, 6 };
  
    printArray(arr, n);
  
 
}
 
}
//contributed by Arnab Kundu

Python3

# Python 3 program to print array elements
# in alternative increasing and decreasing
# order
 
# Function to print array elements in
# alternative increasing and decreasing
# order
def printArray(arr, n):
 
    # First sort the array in
    # increasing order
    arr.sort()
 
    l = 0
    r = n - 1
    flag = 0
     
    # start with 2 elements in
    # increasing order
    k = 2
 
    # till all the elements are not printed
    while (l <= r) :
         
        # printing the elements in
        # increasing order
        if (flag == 0):
            i = l
            while i < l + k and i <= r:
                print(arr[i], end = " ")
                i += 1
 
            flag = 1
            l = i
         
        else:     # printing the elements in
                 # decreasing order
            i = r
            while i > r - k and i >= l:
                print(arr[i], end = " ")
                i -= 1
 
            flag = 0
            r = i
 
        # increasing the number of elements
        # to printed in next iteration
        k += 1
 
# Driver Code
if __name__ == "__main__":
     
    n = 6
    arr = [ 1, 2, 3, 4, 5, 6 ]
    printArray(arr, n)
 
# This code is contributed by ita_c

C#

// C# program to print array elements in
// alternative increasing and decreasing
// order
using System;
  
class GFG{
      
// Function to print array elements in
// alternative increasing and decreasing
// order
static void printArray(int []arr, int n)
{
     
    // First sort the array
    // in increasing order
    Array.Sort(arr);
  
    int l = 0, r = n - 1, flag = 0, i;
  
    // start with 2 elements in
    // increasing order
    int k = 2;
  
    // till all the elements
    // are not printed
    while (l <= r) {
         
        // printing the elements in
        // increasing order
        if (flag == 0) {
             
            for (i = l; i < l + k && i <= r; i++)
                    Console.Write(arr[i] + " ");
  
            flag = 1;
            l = i;
        }
        else
         
        // printing the elements in
        // decreasing order
        {
            for (i = r; i > r - k && i >= l; i--)
                Console.Write(arr[i] + " ");
  
            flag = 0;
            r = i;
        }
  
        // increasing the number of elements
        // to printed in next iteration
        k++;
    }
}
  
// Driver Code
static public void Main ()
{
          
    int n = 6;
    int []arr = { 1, 2, 3, 4, 5, 6 };
    printArray(arr, n);
 
}
}
 
// This code is contributed by Sach_Code

PHP

<?php
// PHP program to print array elements in
// alternative increasing and decreasing
// order
 
// Function to print array elements in
// alternative increasing and decreasing
// order
function printArray($arr, $n)
{
    // First sort the array in
    // increasing order
    sort($arr);
 
    $l = 0;
    $r = $n - 1;
    $flag = 0;
 
    // start with 2 elements in
    // increasing order
    $k = 2;
 
    // till all the elements are
    // not printed
    while ($l <= $r)
    {
        // printing the elements in
        // increasing order
        if ($flag == 0)
        {
            for ($i = $l;
                 $i < $l + $k &&
                 $i <= $r; $i++)
                echo $arr[$i] , " ";
 
            $flag = 1;
            $l = $i;
        }
        else // printing the elements in
             // decreasing order
        {
            for ($i = $r;
                 $i > $r - $k &&
                 $i >= $l; $i--)
                echo $arr[$i] , " ";
 
            $flag = 0;
            $r = $i;
        }
 
        // increasing the number of elements
        // to printed in next iteration
        $k++;
    }
}
 
// Driver Code
$n = 6;
$arr = array( 1, 2, 3, 4, 5, 6 );
 
printArray($arr, $n);
 
// This code is contributed by jit_t
?>

Javascript

<script>
 
// Javascript program to print array elements in
// alternative increasing and decreasing
// order
 
// Function to print array elements in
// alternative increasing and decreasing
// order
function printArray(arr, n)
{
     
    // First sort the array
    // in increasing order
    arr.sort();
 
    let l = 0, r = n - 1, flag = 0, i;
 
    // start with 2 elements in
    // increasing order
    let k = 2;
 
    // till all the elements
    // are not printed
    while (l <= r)
    {
         
        // printing the elements in
        // increasing order
        if (flag == 0)
        {
            for(i = l; i < l + k && i <= r; i++)
                document.write(arr[i] + " ");
 
            flag = 1;
            l = i;
        }
        else
 
        // Printing the elements in
        // decreasing order
        {
            for(i = r; i > r - k && i >= l; i--)
                document.write(arr[i] + " ");
 
            flag = 0;
            r = i;
        }
 
        // Increasing the number of elements
        // to printed in next iteration
        k++;
    }
}
 
// Driver code
let n = 6;
let arr = [ 1, 2, 3, 4, 5, 6 ];
printArray(arr, n);
 
// This code is contributed by suresh07
 
</script>
Producción: 

1 2 6 5 4 3

 

Complejidad de tiempo: O(nlogn)
Espacio auxiliar: O(1) 

Publicación traducida automáticamente

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