Rearrange given Array by splitting in half and inserting second half in reverse at alternate position
Last Updated :
10 Mar, 2022
Given an array arr[] of even length N, the task is to perform the following operations on the given array:
- Split the given array in half.
- Insert the second half in reverse order at alternate positions from the start.
Examples:
Input: N = 6, arr[] = {1, 2, 3, 4, 5, 6}
Output: 1 6 2 5 3 4
Explanation: The first element is 1.
Then print the last element 6
Then the 2nd element 2 followed by the 2nd last element (i.e. the 5th element) 5.
Now print the 3rd element which is 3 and the 3rd last (i.e. the 4th element) 4.
Input: N = 4, arr[] = {12, 34, 11, 20}
Output: 12 20 34 11
Approach: This problem is solved by splitting the array into two parts with the help of two pointers i starting from 0 and j starting from (N-1). Now print the elements at i and j alternatively and increment i/ decrement j when an element at ith / jth position is inserted in new array.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > printAlternate( int arr[], int N)
{
int i = 0, j = N - 1;
vector< int > ans;
while (i <= j) {
ans.push_back(arr[i]);
ans.push_back(arr[j]);
i = i + 1;
j = j - 1;
}
return ans;
}
int main()
{
int N = 6;
int arr[N] = { 1, 2, 3, 4, 5, 6 };
vector< int > ans = printAlternate(arr, N);
for ( int x : ans)
cout << x << " " ;
return 0;
}
|
Java
import java.util.*;
class GFG {
public static ArrayList<Integer>
printAlternate( int [] arr, int N)
{
int i = 0 , j = N - 1 ;
ArrayList<Integer> ans = new ArrayList<>();
while (i <= j) {
ans.add(arr[i]);
ans.add(arr[j]);
i = i + 1 ;
j = j - 1 ;
}
return ans;
}
public static void main(String[] args)
{
int N = 6 ;
int arr[] = { 1 , 2 , 3 , 4 , 5 , 6 };
ArrayList<Integer> ans = printAlternate(arr, N);
for ( int x : ans)
System.out.print(x + " " );
}
}
|
Python3
def printAlternate(arr, N):
i = 0
j = N - 1
ans = []
while (i < = j):
ans.append(arr[i])
ans.append(arr[j])
i = i + 1
j = j - 1
return ans
N = 6
arr = [ 1 , 2 , 3 , 4 , 5 , 6 ]
ans = printAlternate(arr, N)
for x in ans:
print (x, end = ' ' )
|
C#
using System;
using System.Collections;
class GFG {
static ArrayList printAlternate( int [] arr, int N)
{
int i = 0, j = N - 1;
ArrayList ans = new ArrayList();
while (i <= j) {
ans.Add(arr[i]);
ans.Add(arr[j]);
i = i + 1;
j = j - 1;
}
return ans;
}
public static void Main()
{
int N = 6;
int [] arr = { 1, 2, 3, 4, 5, 6 };
ArrayList ans = printAlternate(arr, N);
foreach ( int x in ans) Console.Write(x + " " );
}
}
|
Javascript
<script>
function printAlternate(arr, N)
{
let i = 0, j = N - 1;
let ans = [];
while (i <= j) {
ans.push(arr[i]);
ans.push(arr[j]);
i = i + 1;
j = j - 1;
}
return ans;
}
let N = 6;
let arr = [1, 2, 3, 4, 5, 6];
let ans = printAlternate(arr, N);
for (let x of ans)
document.write(x + " " );
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...