Reorganice la array cambiando los elementos intermedios para que comiencen y terminen alternativamente

Dada una array, la tarea es desplazar el elemento central al principio y al final de la array alternativamente, hasta que el elemento central sea igual al primer elemento de la array original.

Entrada: arr[]=[2, 8, 5, 9, 10]
Salida: [9, 5, 2, 10, 8]
Explicación: Podemos obtener esta salida desplazando el elemento central
paso 1: el elemento central 5 se desplaza al frente de la array [5, 2, 8, 9, 10]
paso 2: el elemento central 8 se desplaza al final de la array [5, 2, 9, 10, 8]
paso 3: el elemento central 9 se desplaza al frente de la array [9, 5 , 2, 10, 8]

Entrada: array[]=[10, 12, 6, 5, 3, 1]
Salida: [1, 3, 5, 10, 6, 12]

Enfoque ingenuo: cambie el elemento central de la array alternativamente al inicio y al final de la array.
Tome el elemento del medio y muévalo al comienzo de la array si c es par o muévalo al final de la array si c es impar. Termine el ciclo cuando el elemento del medio sea igual al primer elemento de la array original.

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

C++

// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function for shifting middle element.
void AlternateShift(vector<int>& arr, int x)
{
 
    // get middle index
    int mid = arr.size() / 2;
 
    // initialize c to 0
    int c = 0;
   
    // Shift middle element
    // till its value not equals to x.
    while (arr[mid] != x) {
 
        // pop middle element
 
        int z = arr[mid];
        arr.erase(arr.begin() + mid);
 
        // if c is even then insert z
        // at start of the array
        if (c % 2 == 0)
            arr.insert(arr.begin() + 0, z);
 
        // if c is odd then insert z
        // at end of the array
        else
            arr.push_back(z);
 
        // increment count c
        c += 1;
    }
}
 
int main()
{
    vector<int> Arr = { 2, 8, 5, 9, 10 };
 
    // initialize a to zero index array value
    int a = Arr[0];
 
    // call AlternateShift function
    AlternateShift(Arr, a);
 
    // print the changed array Unpacking array
    for (int i = 0; i < Arr.size(); ++i) {
        cout << Arr[i] << " ";
    }
 
    return 0;
}
 
    // This code is contributed by rakeshsahni

Python3

# Function for shifting middle element.
def AlternateShift(arr, x):
 
    # get middle index
    mid = len(arr) // 2
 
    # initialize c to 0
    c = 0
 
    # Shift middle element
    # till its value not equals to x.
    while arr[mid] != x:
 
        # pop middle element
        z = arr.pop(mid)
 
        # if c is even then insert z
        # at start of the array
        if c % 2 == 0:
            arr.insert(0, z)
 
        # if c is odd then insert z
        # at end of the array
        else:
            arr.append(z)
 
        # increment count c
        c += 1
 
 
Arr = [2, 8, 5, 9, 10]
 
# initialize a to zero index array value
a = Arr[0]
 
# call AlternateShift function
AlternateShift(Arr, a)
 
# print the changed array Unpacking array
print(*Arr)

Javascript

<script>
    // JavaScript program for above approach
 
    // Function for shifting middle element.
    const AlternateShift = (arr, x) => {
 
        // get middle index
        let mid = parseInt(arr.length / 2);
 
        // initialize c to 0
        let c = 0;
 
        // Shift middle element
        // till its value not equals to x.
        while (arr[mid] != x) {
 
            // pop middle element
 
            let z = arr[mid];
            arr.splice(mid, 1);
 
            // if c is even then insert z
            // at start of the array
            if (c % 2 == 0)
                arr.splice(0, 0, z);
 
            // if c is odd then insert z
            // at end of the array
            else
                arr.push(z);
 
            // increment count c
            c += 1;
        }
    }
 
    Arr = [2, 8, 5, 9, 10];
 
    // initialize a to zero index array value
    let a = Arr[0];
 
    // call AlternateShift function
    AlternateShift(Arr, a);
 
    // print the changed array Unpacking array
 
    for (let i = 0; i < Arr.length; ++i) {
        document.write(`${Arr[i]} `);
    }
 
// This code is contributed by rakeshsahni
 
</script>
Producción

9 5 2 10 8

Tiempo Complejidad: O(n 2 )
Espacio Auxiliar: O(1)

Enfoque eficiente: el cambio alternativo también es el caso de la mitad de la inversión de la array. Primero tome un elemento del último al medio si n es par o tome un elemento del último segundo al medio e insértelo en la nueva array br[], luego inserte el primer elemento en br[]. Luego inserte el elemento desde mid-1 hasta el índice 1 e insértelo en br[]. Por lo tanto, devolverá la array en medio orden de inversión.

Algoritmo:

paso 1: declarar nueva array br e inicializar pos como n-1.
Paso 2: si n es par, atraviesa desde el último índice pos o si n es impar, entonces atraviesa desde el penúltimo índice pos-1.
paso 3: almacene el elemento desde el índice pos hasta el índice medio en la array br.
paso 4: luego inserte el primer elemento de la array en la array br. 
paso 5: si n es impar, inserte el último elemento de valor de la array en la array br.
paso 6: almacene el elemento desde el índice mid-1 hasta el índice 1 en la array br.
paso 7: devuelve la array br.

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

C++

// C++ Program of the above approach
#include <iostream>
using namespace std;
 
// Function to to shift the middle
// element to the start and end of
// the array alternatively, till
// the middle element becomes equal to
// the first element of the original Array
int* rearrange(int* ar, int n)
{
    // creating the array to store
    // rearranged value
    int* br = new int[n];
 
    // initialising pos to last index
    int pos = n - 1;
 
    // if n is odd then we will
    // transverse the array
    // from second last element
    if (n % 2 != 0)
        pos = pos - 1;
 
    // storing index of middle element
    int mid = n / 2;
 
    // index variable for rearranged array
    int c = 0;
 
    // transversing the array from
    // the pos to mid index
    // and storing it in br[] array
    for (; pos >= mid; pos--)
        br = ar[pos];
 
    // storing the first element as
    // mid value
    br = ar[0];
 
    // if n is odd then store
    // the last value in br[] the
    // transverse till 1st index
    if (n % 2 != 0)
        br = ar[n - 1];
 
    // storing the first element of
    // array as mid value
    for (; pos >= 1; pos--)
        br = ar[pos];
 
    // returning br[] array
    return br;
}
// Driver Code
int main()
{
    int ar[] = { 2, 8, 5, 9, 10 };
    int n = sizeof(ar) / sizeof(ar[0]);
 
    // Function Call
    int* res = rearrange(ar, n);
 
    // Print answer
    for (int i = 0; i < n; i++)
        cout << res[i] << " ";
}

Java

// Java Program of the above approach
import java.util.*;
 
class GFG
{
 
// Function to to shift the middle
// element to the start and end of
// the array alternatively, till
// the middle element becomes equal to
// the first element of the original Array
static int[] rearrange(int[] ar, int n)
{
   
    // creating the array to store
    // rearranged value
    int[] br = new int[n];
 
    // initialising pos to last index
    int pos = n - 1;
 
    // if n is odd then we will
    // transverse the array
    // from second last element
    if (n % 2 != 0)
        pos = pos - 1;
 
    // storing index of middle element
    int mid = n / 2;
 
    // index variable for rearranged array
    int c = 0;
 
    // transversing the array from
    // the pos to mid index
    // and storing it in br[] array
    for (; pos >= mid; pos--)
        br = ar[pos];
 
    // storing the first element as
    // mid value
    br = ar[0];
 
    // if n is odd then store
    // the last value in br[] the
    // transverse till 1st index
    if (n % 2 != 0)
        br = ar[n - 1];
 
    // storing the first element of
    // array as mid value
    for (; pos >= 1; pos--)
        br = ar[pos];
 
    // returning br[] array
    return br;
}
   
// Driver Code
public static void main(String[] args)
{
    int ar[] = { 2, 8, 5, 9, 10 };
    int n = ar.length;
 
    // Function Call
    int[] res = rearrange(ar, n);
 
    // Print answer
    for (int i = 0; i < n; i++)
        System.out.print(res[i]+ " ");
}
}
 
// This code is contributed by Amit Katiyar

Python3

# Python 3 Program of the above approach
 
# Function to to shift the middle
# element to the start and end of
# the array alternatively, till
# the middle element becomes equal to
# the first element of the original Array
def rearrange(ar, n):
    # creating the array to store
    # rearranged value
    br = [0 for i in range(n)]
 
    # initialising pos to last index
    pos = n - 1
 
    # if n is odd then we will
    # transverse the array
    # from second last element
    if (n % 2 != 0):
        pos = pos - 1
 
    # storing index of middle element
    mid = n // 2
 
    # index variable for rearranged array
    c = 0
 
    # transversing the array from
    # the pos to mid index
    # and storing it in br[] array
    while(pos >= mid):
        br = ar[pos]
        c += 1
        pos -= 1
 
    # storing the first element as
    # mid value
    br = ar[0]
    c += 1
 
    # if n is odd then store
    # the last value in br[] the
    # transverse till 1st index
    if (n % 2 != 0):
        br = ar[n - 1]
        c += 1
 
    # storing the first element of
    # array as mid value
    while(pos >= 1):
        br = ar[pos]
        c += 1
        pos -= 1
 
    # returning br[] array
    return br
 
# Driver Code
if __name__ == '__main__':
    ar = [2, 8, 5, 9, 10]
    n = len(ar)
 
    # Function Call
    res = rearrange(ar, n)
 
    # Print answer
    for i in range(n):
        print(res[i],end = " ")
         
        # This code is contributed by ipg2016107.

C#

// C# Program of the above approach
using System;
 
public class GFG
{
 
// Function to to shift the middle
// element to the start and end of
// the array alternatively, till
// the middle element becomes equal to
// the first element of the original Array
static int[] rearrange(int[] ar, int n)
{
   
    // creating the array to store
    // rearranged value
    int[] br = new int[n];
 
    // initialising pos to last index
    int pos = n - 1;
 
    // if n is odd then we will
    // transverse the array
    // from second last element
    if (n % 2 != 0)
        pos = pos - 1;
 
    // storing index of middle element
    int mid = n / 2;
 
    // index variable for rearranged array
    int c = 0;
 
    // transversing the array from
    // the pos to mid index
    // and storing it in br[] array
    for (; pos >= mid; pos--)
        br = ar[pos];
 
    // storing the first element as
    // mid value
    br = ar[0];
 
    // if n is odd then store
    // the last value in br[] the
    // transverse till 1st index
    if (n % 2 != 0)
        br = ar[n - 1];
 
    // storing the first element of
    // array as mid value
    for (; pos >= 1; pos--)
        br = ar[pos];
 
    // returning br[] array
    return br;
}
   
// Driver Code
public static void Main(String[] args)
{
    int []ar = { 2, 8, 5, 9, 10 };
    int n = ar.Length;
 
    // Function Call
    int[] res = rearrange(ar, n);
 
    // Print answer
    for (int i = 0; i < n; i++)
        Console.Write(res[i]+ " ");
}
}
 
// This code is contributed by Amit Katiyar

Javascript

<script>
// javascript Program of the above approach
 
// Function to to shift the middle
// element to the start and end of
// the array alternatively, till
// the middle element becomes equal to
// the first element of the original Array
function rearrange(ar , n)
{
   
    // creating the array to store
    // rearranged value
    var br = Array.from({length: n}, (_, i) => 0);
 
    // initialising pos to last index
    var pos = n - 1;
 
    // if n is odd then we will
    // transverse the array
    // from second last element
    if (n % 2 != 0)
        pos = pos - 1;
 
    // storing index of middle element
    var mid = parseInt(n / 2);
 
    // index variable for rearranged array
    var c = 0;
 
    // transversing the array from
    // the pos to mid index
    // and storing it in br array
    for (; pos >= mid; pos--)
        br = ar[pos];
 
    // storing the first element as
    // mid value
    br = ar[0];
 
    // if n is odd then store
    // the last value in br the
    // transverse till 1st index
    if (n % 2 != 0)
        br = ar[n - 1];
 
    // storing the first element of
    // array as mid value
    for (; pos >= 1; pos--)
        br = ar[pos];
 
    // returning br array
    return br;
}
   
// Driver Code
    var ar = [ 2, 8, 5, 9, 10 ];
    var n = ar.length;
 
    // Function Call
    var res = rearrange(ar, n);
 
    // Print answer
    for (var i = 0; i < n; i++)
        document.write(res[i]+ " ");
 
// This code is contributed by Princi Singh
</script>
Producción

9 5 2 10 8 

Complejidad temporal: O(n)
Complejidad espacial: O(n)

Publicación traducida automáticamente

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