Imprimir elementos alternativos de una array

Dada una array , arr[] de tamaño N , la tarea es imprimir los elementos de la array dada presentes en índices impares ( indexación basada en 1 ).

Ejemplos:

Entrada: arr[] = {1, 2, 3, 4, 5}
Salida: 1 3 5
Explicación:
Los elementos de array presentes en posiciones impares son: {1, 3, 5}.
Por lo tanto, la salida requerida es 1 3 5.

Entrada: arr[] = {-5, 1, 4, 2, 12}
Salida: -5 4 12

 

Enfoque ingenuo: el enfoque más simple para resolver este problema es recorrer la array dada y verificar si la posición del elemento actual es impar o no. Si se encuentra que es cierto, imprima el elemento actual.

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

C++

// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to print
// Alternate elements
// of the given array
void printAlter(int arr[], int N)
{
    // Print elements
    // at odd positions
    for (int currIndex = 0;
         currIndex < N; currIndex++) {
 
        // If currIndex stores even index
        // or odd position
        if (currIndex % 2 == 0) {
            cout << arr[currIndex] << " ";
        }
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
    printAlter(arr, N);
}

C

// C program to implement
// the above approach
 
#include <stdio.h>
 
// Function to print
// Alternate elements
// of the given array
void printAlter(int arr[], int N)
{
    // Print elements
    // at odd positions
    for (int currIndex = 0;
         currIndex < N; currIndex++) {
 
        // If currIndex stores even index
        // or odd position
        if (currIndex % 2 == 0) {
            printf("%d ", arr[currIndex]);
        }
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
    printAlter(arr, N);
}

Java

// Java program to implement
// the above approach
import java.io.*;
 
class GFG{
 
// Function to print
// Alternate elements
// of the given array
static void printAlter(int[] arr, int N)
{
     
    // Print elements
    // at odd positions
    for(int currIndex = 0;
            currIndex < N;
            currIndex++)
    {
         
        // If currIndex stores even index
        // or odd position
        if (currIndex % 2 == 0)
        {
            System.out.print(arr[currIndex] + " ");
        }
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int[] arr = { 1, 2, 3, 4, 5 };
    int N = arr.length;
     
    printAlter(arr, N);
}
}
 
// This code is contributed by akhilsaini

Python3

# Python3 program to implement
# the above approach
 
# Function to print
# Alternate elements
# of the given array
def printAlter(arr, N):
     
    # Print elements
    # at odd positions
    for currIndex in range(0, N):
         
        # If currIndex stores even index
        # or odd position
        if (currIndex % 2 == 0):
            print(arr[currIndex], end = " ")
 
# Driver Code
if __name__ == "__main__":
     
    arr = [ 1, 2, 3, 4, 5 ]
    N = len(arr)
     
    printAlter(arr, N)
 
# This code is contributed by akhilsaini

C#

// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to print
// Alternate elements
// of the given array
static void printAlter(int[] arr, int N)
{
     
    // Print elements
    // at odd positions
    for(int currIndex = 0;
            currIndex < N;
            currIndex++)
    {
         
        // If currIndex stores even index
        // or odd position
        if (currIndex % 2 == 0)
        {
            Console.Write(arr[currIndex] + " ");
        }
    }
}
 
// Driver Code
public static void Main()
{
    int[] arr = { 1, 2, 3, 4, 5 };
    int N = arr.Length;
     
    printAlter(arr, N);
}
}
 
// This code is contributed by akhilsaini

Javascript

// javascript program to implement
// the above approach
 
// Function to print
// Alternate elements
// of the given array
function printAlter(arr, N)
{
      
    // Print elements
    // at odd positions
    for(var currIndex = 0; currIndex < N; currIndex++)
    {
          
        // If currIndex stores even index
        // or odd position
        if (currIndex % 2 == 0)
        {
            document.write(arr[currIndex] + " ");
        }
    }
}
  
// Driver Code
 
    var arr = [ 1, 2, 3, 4, 5 ]
    var N = arr.length;
      
    printAlter(arr, N);
 
 // This code is contributed by bunnyram19.
Producción: 

1 3 5

 

Complejidad temporal: O(N)
Espacio auxiliar: O(1)

Enfoque eficiente: para optimizar el enfoque anterior, la idea es atravesar solo aquellos elementos de la array dada que están presentes en posiciones impares. Siga los pasos a continuación para resolver el problema:

  • Iterar un bucle con una variable de bucle currIndex de 0 a N.
  • Imprima el valor de arr[currIndex] e incremente el valor de currIndex en 2 hasta que currIndex exceda N.

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

C++

// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to print
// Alternate elements
// of the given array
void printAlter(int arr[], int N)
{
    // Print elements
    // at odd positions
    for (int currIndex = 0;
         currIndex < N; currIndex += 2) {
 
        // Print elements of array
        cout << arr[currIndex] << " ";
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
    printAlter(arr, N);
}

C

// C program to implement
// the above approach
 
#include <stdio.h>
 
// Function to print
// Alternate elements
// of the given array
void printAlter(int arr[], int N)
{
    // Print elements
    // at odd positions
    for (int currIndex = 0;
         currIndex < N; currIndex += 2) {
 
        // Print elements of array
        printf("%d ", arr[currIndex]);
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
    printAlter(arr, N);
}

Java

// Java program to implement
// the above approach
import java.io.*;
 
class GFG{
 
// Function to print
// Alternate elements
// of the given array
static void printAlter(int[] arr, int N)
{
     
    // Print elements
    // at odd positions
    for(int currIndex = 0;
            currIndex < N;
            currIndex += 2)
    {
         
        // Print elements of array
        System.out.print(arr[currIndex] + " ");
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int[] arr = { 1, 2, 3, 4, 5 };
    int N = arr.length;
     
    printAlter(arr, N);
}
}
 
// This code is contributed by akhilsaini

Python3

# Python3 program to implement
# the above approach
 
# Function to print
# Alternate elements
# of the given array
def printAlter(arr, N):
     
    # Print elements
    # at odd positions
    for currIndex in range(0, N, 2):
         
        # Print elements of array
        print(arr[currIndex], end = " ")
 
# Driver Code
if __name__ == "__main__":
 
    arr = [ 1, 2, 3, 4, 5 ]
    N = len(arr)
     
    printAlter(arr, N)
 
# This code is contributed by akhilsaini

C#

// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to print
// Alternate elements
// of the given array
static void printAlter(int[] arr, int N)
{
     
    // Print elements
    // at odd positions
    for(int currIndex = 0;
            currIndex < N;
            currIndex += 2)
    {
         
        // Print elements of array
        Console.Write(arr[currIndex] + " ");
    }
}
 
// Driver Code
public static void Main()
{
    int[] arr = { 1, 2, 3, 4, 5 };
    int N = arr.Length;
     
    printAlter(arr, N);
}
}
 
// This code is contributed by akhilsaini

Javascript

<script>
 
// Function to print
// Alternate elements
// of the given array
function printAlter(arr, N)
{
    // Print elements
    // at odd positions
    for (var currIndex = 0;
        currIndex < N; currIndex += 2)
        {
 
        // Print elements of array
        document.write( arr[currIndex] + " ");
    }
}
 
var arr= [ 1, 2, 3, 4, 5 ];
    var N = 5;
    printAlter(arr, N);
 
 
</script>
Producción: 

1 3 5

 

Complejidad temporal: O(N)
Espacio auxiliar: O(1)

Método 3: Usando Slicing en Python:

Rebane usando la lista de rebanado de python estableciendo el valor de paso en 2.

A continuación se muestra la implementación:

Python3

# Python3 program to implement
# the above approach
 
# Function to print
# Alternate elements
# of the given array
def printAlter(arr, N):
 
    # Print elements
    # at odd positions by using slicing
    # we use * to print with spaces
    print(*arr[::2])
 
 
# Driver Code
if __name__ == "__main__":
 
    arr = [1, 2, 3, 4, 5]
    N = len(arr)
 
    printAlter(arr, N)
 
# This code is contributed by vikkycirus

Producción:

1 3 5

Complejidad de tiempo: O(N)

Complejidad espacial: O(1)

Publicación traducida automáticamente

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