![]() |
VOOZH | about |
We have an array of the form {a0, a1, a2....., an, b0, b1, b2, .....bn} and our task is to rearrange the same in theform given below by using O(1) space-
{a0, b0, a1, b1, a2, b2...........an, bn}
Examples:
Input : arr[] = {1, 3, 5, 7, 2, 4, 6, 8}
Output : {1, 2, 3, 4, 5, 6, 7, 8}
Input : arr[] = {11, 13, 15, 12, 14, 16}
Output : {11, 12, 13, 14, 15, 16}
We have already discussed two approaches-
As we can see we have to transform the array so there must be an even size array.To rearrange the array we will start from the middle of the array and each time we will shift 1 element of the second half to left at it's desired position. This algorithm will take O(n^2).
Algorithm-
1- Take the input array
2- If size is null or odd return
3- find the middle index of the array
4- While (midindex>0)
set count = midindex and
swapindex = midindex
while (count-->0){
swap(swapindex+1, swapindedx)
swapindex++
}
midindex--
5- End
Working-
array- 1 3 5 7 2 4 6 8 1st Loop- 1 2 3 5 7 4 6 8 2nd Loop- 1 2 3 4 5 7 6 8 3rd loop- 1 2 3 4 5 6 7 8
Output:
1 2 3 4 5 6
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach:
Note: The assumption is that the largest value in the array is INT_MAX/2 and consists of only positive integers
The algorithm utilizes bit manipulation techniques to rearrange an array [x1,x2,...,xn,y1,y2,...,yn].
It is based on the constraint that 1 <= nums[i] <= INT_MAX/2.
Implementation:
The algorithm has two parts, loop 1 and loop 2.
To store two numbers in one binary representation, two pointers i and j are used.
i starts from n and moves backwards to 0, while j starts from the end of the array and moves backwards to n.
Code:
1 2 3 4 5 6
Complexity Analysis