![]() |
VOOZH | about |
Given an array of n elements. Our task is to write a program to rearrange the array such that elements at even positions are greater than all elements before it and elements at odd positions are less than all elements before it.
Examples:
Input : arr[] = {1, 2, 3, 4, 5, 6, 7}
Output : 4 5 3 6 2 7 1
Input : arr[] = {1, 2, 1, 4, 5, 6, 8, 8}
Output : 4 5 2 6 1 8 1 8
The idea to solve this problem is to first create an additional copy of the original array and sort the copied array. Now the total number of even positions in an array with n elements will be floor(n/2) and the remaining is the number of odd positions. Now fill the odd and even positions in the original array using the sorted array in a below manner:
Below is the implementation of above idea:
4 5 3 6 2 7 1
Time Complexity: O( n logn )
Auxiliary Space: O(n)
Another Approach-
We can traverse the array by defining two variables p and q and assign values from last.
if even index is there, we will give it max value otherwise min value.
p =0 and q= end;
p will go ahead and q will decrease.
4 5 2 6 1 8 1 8
Time Complexity: O(n log n), The maximum time taken to sort the array.
Auxiliary Space: O(n), The extra space is required to store the copy of elements of original array.
This algorithm will take 1 for loop less than the previous one.