# Divide and Conquer – Rearrange array elements in special order

**Objective**: Given an array of integers of size 2n, write an algorithm to arrange them such that first n elements and last n elements are set up in alternative manner. Say n = 3 and 2n elements are {x1, x2, x3, y1, y2, y3} , then result should be {x1, y1, x2, y2, x3, y3}

**Example**:

A [] = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10}, n= 5 Output: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

**Approaches:**

**Brute Force:**

One by one shift all the elements from the second half of the array to their correct positions in the left half of the array.

**Time Complexity: O(n^2)**

See the explanation below-

**Code**:

**Output:**

1 2 3 4 5 6 7 8 9 10

**Divide and Conquer:**

- This solution will work only if the total number of elements is in 2i So total elements are either 2 or 4 or 8 or 16 ….and so on.
- Total length is 2n, take n elements around middle element.
- Swap n/2 elements on the left side from the middle element with n/2 elements on the right side from the middle element.
- Now divide the array into 2 parts, first n elements and last n elements.
- Repeat step 2, 3 on both the parts recursively.

**Time Complexity: O(nlogn)**

See the explanation below-

**Code**:

**Output**:

[1, 2, 3, 4, 5, 6, 7, 8]

This was asked in Microsoft

For the brute force approach, in the explanation in figure, the last step output should be 1, 2, 3, 4, 5, 6

Line 7 in Brute Force Approach, it should be start < mid