Rearrange the Array by shifting middle elements to start and end alternatively

Given an array, the task is 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.
Input: arr[]=[2, 8, 5, 9, 10]Output: [9, 5, 2, 10, 8]Explanation: We can get this output by shifting middle element
step1: middle element 5 is shifted to front of array [5, 2, 8, 9, 10]step2: middle element 8 is shifted to end of array [5, 2, 9, 10, 8]step3: middle element 9 is shifted to front of array [9, 5, 2, 10, 8]
Input: arr[]=[10, 12, 6, 5, 3, 1]Output: [1, 3, 5, 10, 6, 12]
Naive Approach: Shift the middle element of the array alternatively to the start and end of the array.
Take the middle element and shift it to the start of the Array if c is even or shift it to the end of Array if c is odd. Terminate the loop when the middle element becomes equal to the first element of the Original Array.
Below is the implementation of the above approach :
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 |
Java
// Java program for above approachÂ
import java.util.*;Â
class GFG {    // Function for shifting middle element.    static void alternateShift(ArrayList<Integer> 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.get(mid) != x) {            // pop middle element            int z = arr.get(mid);            arr.remove(mid);Â
            // if c is even then insert z            // at start of the array            if (c % 2 == 0) {                arr.add(0, z);            }            // if c is odd then insert z            // at end of the array            else {                arr.add(z);            }Â
            // increment count c            c++;        }    }Â
    public static void main(String[] args) {        ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(2, 8, 5, 9, 10));Â
        // initialize a to zero index array value        int a = arr.get(0);Â
        // call AlternateShift function        alternateShift(arr, a);Â
        // print the changed array Unpacking array        for (int i = 0; i < arr.size(); ++i) {            System.out.print(arr.get(i) + " ");        }             }} |
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 valuea = Arr[0]Â
# call AlternateShift functionAlternateShift(Arr, a)Â
# print the changed array Unpacking arrayprint(*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> |
C#
// C# program for above approachÂ
using System;using System.Collections.Generic;using System.Linq;Â
public class GFG {Â
    // Function for shifting middle element.    static void AlternateShift(List<int> arr, int x)    {        // get middle index        int mid = arr.Count / 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.RemoveAt(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.Add(z);            }Â
            // increment count c            c++;        }    }Â
    static public void Main()    {Â
        // Code        List<int> arr = new List<int>{ 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.Count; ++i) {            Console.Write(arr[i] + " ");        }    }}Â
// This code is contributed by lokesh. |
9 5 2 10 8
Time Complexity: O(n2)
Auxiliary Space: O(1)
Efficient Approach: Alternate Shifting is also the case of half reversal of array. First take an element from last to mid if n is even or take an element from last second to mid and insert into new array br[], then insert the first element into br[]. Then insert element from mid-1 to index 1 and insert into br[]. So it will return the array in half reversal order.
Algorithm :
step1: Declare new array br and initialize pos as n-1.
step2: If n is even traverse from last index pos or if n is odd then traverse from second last index pos-1.
step3: Store element from pos index to mid index into br array.
step4: Then insert first element of array to br array.Â
step5: If n is odd then insert last value elementof array to br array.
step6: Store element from mid-1 index to index 1 into br array.
step7: return br array.
Below is the implementation of the above algorithm :
C++
// C++ Program of the above approach#include <iostream>using namespace std;Â
// Function 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 Arrayint* 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 Codeint 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 approachimport java.util.*;Â
class GFG{Â
// Function 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 Arraystatic 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 Codepublic 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 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 Arraydef 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 Codeif __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 approachusing System;Â
public class GFG{Â
// Function 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 Arraystatic 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 Codepublic 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 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 Arrayfunction 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> |
9 5 2 10 8
Time Complexity: O(n)
Space Complexity: O(n)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!




