Open In App

Rearrange array such that even index elements are smaller and odd index elements are greater

Last Updated : 31 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array, rearrange the array such that : 

  1. If index i is even, arr[i] <= arr[i+1]
  2. If index i is odd, arr[i] >= arr[i+1]

Note: There can be multiple answers.

Examples:  

Input  : arr[] = {2, 3, 4, 5} 
Output : arr[] = {2, 4, 3, 5}
Explanation : Elements at even indexes are
smaller and elements at odd indexes are greater
than their next elements

Note : Another valid answer
is arr[] = {3, 4, 2, 5}

Input  :arr[] = {6, 4, 2, 1, 8, 3}
Output :arr[] = {4, 6, 1, 8, 2, 3}

This problem is similar to sorting an array in the waveform.

  • A simple solution is to sort the array in decreasing order, then starting from the second element, swap the adjacent elements.
  • An efficient solution is to iterate over the array and swap the elements as per the given condition. 

If we have an array of length n, then we iterate from index 0 to n-2 and check the given condition. 
At any point of time if i is even and arr[i] > arr[i+1], then we swap arr[i] and arr[i+1]. Similarly, if i is odd and 
arr[i] < arr[i+1], then we swap arr[i] and arr[i+1].
For the given example: 

Before rearrange, arr[] = {2, 3, 4, 5} 
Start iterating over the array till index 2 (as n = 4) 

First Step: 
At i = 0, arr[i] = 2 and arr[i+1] = 3. As i is even and arr[i] < arr[i+1], don’t need to swap. 
Second step: 
At i = 1, arr[i] = 3 and arr[i+1] = 4. As i is odd and arr[i] < arr[i+1], swap them. 
Now arr[] = {2, 4, 3, 5} 
Third step: 
At i = 2, arr[i] = 3 and arr[i+1] = 5. So, don’t need to swap them

After rearrange, arr[] = {2, 4, 3, 5} 

Flowchart

Flowchart

Implementation:

C++




// CPP code to rearrange an array such that
// even index elements are smaller and odd
// index elements are greater than their
// next.
#include <iostream>
using namespace std;
 
void rearrange(int* arr, int n)
{
    for (int i = 0; i < n - 1; i++) {
        if (i % 2 == 0 && arr[i] > arr[i + 1])
            swap(arr[i], arr[i + 1]);
 
        if (i % 2 != 0 && arr[i] < arr[i + 1])
            swap(arr[i], arr[i + 1]);
    }
}
 
/* Utility that prints out an array in
   a line */
void printArray(int arr[], int size)
{
    for (int i = 0; i < size; i++)
        cout << arr[i] << " ";
 
    cout << endl;
}
 
/* Driver function to test above functions */
int main()
{
    int arr[] = { 6, 4, 2, 1, 8, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << "Before rearranging: \n";
    printArray(arr, n);
 
    rearrange(arr, n);
 
    cout << "After rearranging: \n";
    printArray(arr, n);
 
    return 0;
}


Java




// Java code to rearrange an array such
// that even index elements are smaller
// and odd index elements are greater
// than their next.
 
class GFG {
 
    static void rearrange(int arr[], int n)
    {
 
        int temp;
        for (int i = 0; i < n - 1; i++) {
            if (i % 2 == 0 && arr[i] > arr[i + 1]) {
                temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
            if (i % 2 != 0 && arr[i] < arr[i + 1]) {
                temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }
    }
 
    /* Utility that prints out an array in
    a line */
    static void printArray(int arr[], int size)
    {
        for (int i = 0; i < size; i++)
            System.out.print(arr[i] + " ");
 
        System.out.println();
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 6, 4, 2, 1, 8, 3 };
        int n = arr.length;
 
        System.out.print("Before rearranging: \n");
        printArray(arr, n);
 
        rearrange(arr, n);
 
        System.out.print("After rearranging: \n");
        printArray(arr, n);
    }
}
 
// This code is contributed by Anant Agarwal.


Python3




# Python code to rearrange
# an array such that
# even index elements
# are smaller and odd
# index elements are
# greater than their
# next.
 
def rearrange(arr, n):
 
    for i in range(n - 1):
        if (i % 2 == 0 and arr[i] > arr[i + 1]):
         
            temp = arr[i]
            arr[i]= arr[i + 1]
            arr[i + 1]= temp
         
        if (i % 2 != 0 and arr[i] < arr[i + 1]):
          
            temp = arr[i]
            arr[i]= arr[i + 1]
            arr[i + 1]= temp
            
  
# Utility that prints out an array in
# a line
def printArray(arr, size):
 
    for i in range(size):
        print(arr[i], " ", end ="")
  
    print()
 
# Driver code
 
arr = [ 6, 4, 2, 1, 8, 3 ]
n = len(arr)
  
print("Before rearranging: ")
printArray(arr, n)
  
rearrange(arr, n)
  
print("After rearranging:")
printArray(arr, n);
 
# This code is contributed
# by Anant Agarwal.


C#




// C# code to rearrange an array such
// that even index elements are smaller
// and odd index elements are greater
// than their next.
using System;
 
class GFG {
 
    static void rearrange(int[] arr, int n)
    {
        int temp;
        for (int i = 0; i < n - 1; i++) {
            if (i % 2 == 0 && arr[i] > arr[i + 1])
            {
                temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
             
            if (i % 2 != 0 && arr[i] < arr[i + 1])
            {
                temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }
    }
 
    /* Utility that prints out an array in
    a line */
    static void printArray(int[] arr, int size)
    {
        for (int i = 0; i < size; i++)
            Console.Write(arr[i] + " ");
 
        Console.WriteLine();
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr = { 6, 4, 2, 1, 8, 3 };
        int n = arr.Length;
 
        Console.WriteLine("Before rearranging: ");
        printArray(arr, n);
 
        rearrange(arr, n);
 
        Console.WriteLine("After rearranging: ");
        printArray(arr, n);
    }
}
 
// This code is contributed by vt_m.


PHP




<?php
// PHP code to rearrange an array such
// that even index elements are smaller
// and odd index elements are greater
// than their next.
 
function swap(&$a, &$b)
{
    $temp = $a;
    $a = $b;
    $b = $temp;
}
function rearrange(&$arr, $n)
{
    for ($i = 0; $i < $n - 1; $i++)
    {
        if ($i % 2 == 0 &&
            $arr[$i] > $arr[$i + 1])
            swap($arr[$i], $arr[$i + 1]);
 
        if ($i % 2 != 0 &&
            $arr[$i] < $arr[$i + 1])
            swap($arr[$i], $arr[$i + 1]);
    }
}
 
/* Utility that prints out
an array in a line */
function printArray(&$arr, $size)
{
    for ($i = 0; $i < $size; $i++)
        echo $arr[$i] . " ";
 
    echo "\n";
}
 
// Driver Code
$arr = array(6, 4, 2, 1, 8, 3 );
$n = sizeof($arr);
 
echo "Before rearranging: \n";
printArray($arr, $n);
 
rearrange($arr, $n);
 
echo "After rearranging: \n";
printArray($arr, $n);
 
// This code is contributed
// by ChitraNayal
?>


Javascript




// JavaScript program for the above approach
 
function rearrangeArray(arr) {
// Sort the input array in ascending order.
arr.sort((a, b) => a - b);
 
// Swap adjacent elements starting from the second
// element.
for (let i = 1; i < arr.length - 1; i += 2) {
let temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
 
// Return the rearranged array.
return arr;
}
 
// Create a new array of integers.
let arr = [2, 3, 4, 5];
 
// Rearrange the elements of the array.
let rearrangedArr = rearrangeArray(arr);
 
// Print the rearranged array.
console.log(rearrangedArr.join(' '));
// Output: 2 4 3 5


Output

Before rearranging: 
6 4 2 1 8 3 
After rearranging: 
4 6 1 8 2 3 

Time Complexity: O(N), as we are using a loop to traverse N times, 
Auxiliary Space: O(1), as we are not using any extra space.

Approach: Sort and Swap Adjacent Elements

The “Sort and Swap Adjacent Elements” approach for rearranging an array such that even index elements are smaller and odd index elements are greater can be summarized in the following steps:

  1. Sort the input array in non-decreasing order.
  2. Iterate over the array using a step of 2 to access the odd-indexed elements.
  3. For each odd-indexed element, swap it with the next even-indexed element to meet the required condition.
  4. Return the rearranged array.
     

Here are the detailed steps with an example:

Input: arr = [2, 3, 4, 5]

  1. Sort the input array in non-decreasing order. The sorted array is: [2, 3, 4, 5].
  2. Iterate over the array using a step of 2 to access the odd-indexed elements. The odd-indexed elements are arr[1] and arr[3].
  3. For each odd-indexed element, swap it with the next even-indexed element to meet the required condition. We swap arr[1] with arr[2] to get the array [2, 4, 3, 5].
  4. Return the rearranged array [2, 4, 3, 5].

C++




#include <algorithm>
#include <iostream>
#include <vector>
 
using namespace std;
 
vector<int> rearrange_array(vector<int>& arr)
{
    sort(arr.begin(), arr.end());
    for (int i = 1; i < arr.size() - 1; i += 2) {
        swap(arr[i], arr[i + 1]);
    }
    return arr;
}
 
// Driver code
int main()
{
    vector<int> arr = { 2, 3, 4, 5 };
    vector<int> rearranged_arr = rearrange_array(arr);
    for (int i = 0; i < rearranged_arr.size(); i++) {
        cout << rearranged_arr[i] << " ";
    }
    // Output: 2 4 3 5
    return 0;
}


Java




import java.util.Arrays;
 
public class Main {
    public static void main(String[] args) {
        int[] arr = {2, 3, 4, 5};
        int[] rearrangedArr = rearrangeArray(arr);
        System.out.println(Arrays.toString(rearrangedArr)); // Output: [2, 4, 3, 5]
    }
 
    public static int[] rearrangeArray(int[] arr) {
        Arrays.sort(arr);
        for (int i = 1; i < arr.length - 1; i += 2) {
            int temp = arr[i];
            arr[i] = arr[i + 1];
            arr[i + 1] = temp;
        }
        return arr;
    }
}


Python3




def rearrange_array(arr):
    arr.sort()
    for i in range(1, len(arr)-1, 2):
        arr[i], arr[i+1] = arr[i+1], arr[i]
    return arr
 
#Example
arr = [2, 3, 4, 5]
rearranged_arr = rearrange_array(arr)
print(rearranged_arr)  # Output: [2, 4, 3, 5]


C#




using System;
using System.Collections.Generic;
 
class Program {
    // Rearranges the elements of the input list in a
    // specific way.
    static List<int> RearrangeArray(List<int> arr)
    {
        // Sort the input list in ascending order.
        arr.Sort();
 
        // Swap adjacent elements starting from the second
        // element.
        for (int i = 1; i < arr.Count - 1; i += 2) {
            int temp = arr[i];
            arr[i] = arr[i + 1];
            arr[i + 1] = temp;
        }
 
        // Return the rearranged list.
        return arr;
    }
 
    static void Main(string[] args)
    {
        // Create a new list of integers.
        List<int> arr = new List<int>{ 2, 3, 4, 5 };
 
        // Rearrange the elements of the list.
        List<int> rearrangedArr = RearrangeArray(arr);
 
        // Print the rearranged list.
        foreach(int i in rearrangedArr)
        {
            Console.Write(i + " ");
        }
        // Output: 2 4 3 5
    }
}


Javascript




// JavaScript program for the above approach
 
function rearrangeArray(arr) {
// Sort the input array in ascending order.
arr.sort((a, b) => a - b);
 
// Swap adjacent elements starting from the second
// element.
for (let i = 1; i < arr.length - 1; i += 2) {
let temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
 
// Return the rearranged array.
return arr;
}
 
// Create a new array of integers.
let arr = [2, 3, 4, 5];
 
// Rearrange the elements of the array.
let rearrangedArr = rearrangeArray(arr);
 
// Print the rearranged array.
console.log(rearrangedArr.join(' '));
// Output: 2 4 3 5


Output

[2, 4, 3, 5]

The time complexity of the “Sort and Swap Adjacent Elements” approach for rearranging an array such that even index elements are smaller and odd index elements are greater is O(n log n),

The auxiliary space of this approach is O(1).



Similar Reads

Rearrange array such that even positioned are greater than odd
Given an array arr[] of N elements, sort the array according to the following relations: arr[i] &gt;= arr[i - 1], if i is even, ∀ 1 &lt;= i &lt; Narr[i] &lt;= arr[i - 1], if i is odd, ∀ 1 &lt;= i &lt; NPrint the resultant array. Examples: Input: N = 4, arr[] = {1, 2, 2, 1}Output: 2 1 2 1Explanation: For i = 1, arr[1] &lt;= arr[0]. So, 1 &lt;= 2.For
10 min read
Even numbers at even index and odd numbers at odd index
Given an array of size n containing equal number of odd and even numbers. The problem is to arrange the numbers in such a way that all the even numbers get the even index and odd numbers get the odd index. Required auxiliary space is O(1).Examples : Input : arr[] = {3, 6, 12, 1, 5, 8} Output : 6 3 12 1 8 5 Input : arr[] = {10, 9, 7, 18, 13, 19, 4,
11 min read
Rearrange array such that all even-indexed elements in the Array is even
Given an array arr[], the task is to check if it is possible to rearrange the array in such a way that every even index(1-based indexing) contains an even number. If such a rearrangement is not possible, print "No". Otherwise, print "Yes" and print a possible arrangement Examples: Input: arr[] = {2, 4, 8, 3, 1} Output: Yes 3 4 8 2 1Input: arr[] = {
6 min read
Rearrange Array to minimize difference of sum of squares of odd and even index elements
Given an array arr[] of size N (multiple of 8) where the values in the array will be in the range [a, (a+8*N) -1] (a can be any positive integer), the task is to rearrange the array in a way such that the difference between the sum of squares at odd indices and sum of squares of the elements at even indices is the minimum among all possible rearran
16 min read
Rearrange sorted array such that all odd indices elements comes before all even indices element
Given a sorted array arr[] consisting of N positive integers, the task is to rearrange the array such that all the odd indices elements come before all the even indices elements. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}Output: 2 4 6 8 1 3 5 7 9 Input: arr[] = {0, 3, 7, 7, 10}Output: 3 7 0 7 10 Approach: The given problem can be solved b
12 min read
Rearrange array such that arr[i] &gt;= arr[j] if i is even and arr[i]&lt;=arr[j] if i is odd and j &lt; i
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
11 min read
C++ Program to Rearrange array such that arr[i] &gt;= arr[j] if i is even and arr[i]&lt;=arr[j] if i is odd and j &lt; i
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
3 min read
Java Program to Rearrange array such that arr[i] &gt;= arr[j] if i is even and arr[i]&lt;=arr[j] if i is odd and j &lt; i
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
3 min read
Python3 Program to Rearrange array such that arr[i] &gt;= arr[j] if i is even and arr[i]&lt;=arr[j] if i is odd and j &lt; i
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
3 min read
Php Program to Rearrange array such that arr[i] &gt;= arr[j] if i is even and arr[i]&lt;=arr[j] if i is odd and j &lt; i
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
3 min read
Article Tags :
Practice Tags :