Given an array arr[], rearrange its elements according to 1-based indexing such that for every even index i, arr[i] is greater than or equal to arr[i-1], and for every odd index i, arr[i] is less than or equal to arr[i-1]. Return the rearranged array that satisfies these conditions for all valid indices.
Find the resultant array.[consider 1-based indexing] .
Examples:
Input: arr[] = [1, 2, 2, 1]
Output: [1 2 1 2]
Explanation:
For i = 2, arr[i] >= arr[i-1]. So, 2 >= 1.
For i = 3, arr[i] <= arr[i-1]. So, 1 <= 2.
For i = 4, arr[i] >= arr[i-1]. So, 2 >= 1.Input: arr[] = [1, 3, 2]
Output: [1 3 2]
Explanation:
For i = 2,arr[i] >= arr[i-1]. So,3 >= 1.
For i = 3,arr[i] <= arr[i-1]. So,2 <= 3.
Table of Content
[Approach 1] - Assign Maximum Elements to Even Positions
Observe that array consists of [n/2] even positioned elements. If we assign the largest [n/2] elements to the even positions and the rest of the elements to the odd positions, our problem is solved. Because element at the odd position will always be less than the element at the even position as it is the maximum element and vice versa. Sort the array and assign the first [n/2] elements at even positions.
#include <vector>
#include <algorithm>
using namespace std;
vector<int> rearrangeArray(vector<int> &arr) {
int n = arr.size();
sort(arr.begin(), arr.end());
vector<int> ans(n);
int ptr1 = 0