VOOZH about

URL: https://www.geeksforgeeks.org/dsa/rearrange-given-array-by-splitting-in-half-and-inserting-second-half-in-reverse-at-alternate-position/

⇱ Rearrange given Array by splitting in half and inserting second half in reverse at alternate position - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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.


Output
1 6 2 5 3 4 

Time Complexity: O(N)
Auxiliary Space: O(N)

Comment