VOOZH about

URL: https://www.geeksforgeeks.org/dsa/rearrange-array-such-that-even-positioned-are-greater-than-odd/

⇱ Rearrange array such that even positioned are greater than odd - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Rearrange array such that even positioned are greater than odd

Last Updated : 28 May, 2026

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.

[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.


Output
1 2 1 2 

Time Complexity: O(n * logn), where n is the size of input array .
Auxiliary Space: O(n)

[Approach 2] - Rearranging array by swapping elements

Traverse the array once from left to right and compare each element with its previous one. If a position is even (1-based) and the current element is smaller than the previous element, swap them. If a position is odd (1-based) and the current element is greater than the previous element, swap them. These local swaps ensure the array satisfies the given conditions in a single pass without extra space.


Output
1 2 1 2 

Time Complexity: O(n), where n is the size of input array.
Auxiliary Space: O(1)

Comment
Article Tags: