Rearrange an array such that every odd indexed element is greater than it previous
Last Updated :
12 Jul, 2022
Given an unsorted array, rearrange the array such that the number at the odd index is greater than the number at the previous even index. There may be multiple outputs, we need to print one of them.
Note: Indexing is based on an array, so it always starts from 0.
Examples:
Input : arr[] = {5, 2, 3, 4}
Output : arr[] = {2, 5, 3, 4}
Input : arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}
Output : arr[] = {1, 3, 2, 5, 4, 7, 6, 9, 8}
If the given array has an even length, then it can be done in a single run. Just for each pair of neighbors, put the max in odd position and min in even. So we just start a cycle from the beginning and compare every two elements. Let's say
6, 5, 4, 3, 2, 1 will give us 5, 6, 3, 4, 1, 2
If the array has an odd length, like 6, 5, 4, 3, 2, 1, 100 then it's slightly trickier, we need to run the second, backward cycle again, but starting from the last element. So, 6, 5, 4, 3, 2, 1, 100 after first cycle will be 5, 6, 3, 4, 1, 2, 100 and after second cycle 5, 6, 3, 4, 1, 100, 2
Implementation:
C++
// C++ program to rearrange array such that
// odd indexed elements are greater.
#include<bits/stdc++.h>
using namespace std;
void rearrange(int arr[], int n)
{
// Common code for odd and even lengths
for (int i=0; i<n-1; i=i+2)
{
if (arr[i] > arr[i+1])
swap(arr[i], arr[i+1]);
}
// If length is odd
if (n & 1)
{
for (int i=n-1; i>0; i=i-2)
if (arr[i] > arr[i-1])
swap(arr[i], arr[i-1]);
}
}
/* Utility that prints out an array on a line */
void printArray(int arr[], int size)
{
for (int i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
/* Driver function to test above functions */
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
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 program to rearrange array such that
// odd indexed elements are greater.
import java.util.Arrays;
class GFG
{
// Utility function to Swap two variables
public static void swap(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// method to rearrange array such that
// odd indexed elements are greater.
public static void Rearrange(int[] arr, int n)
{
// Common code for odd and even lengths
for (int i = 0; i < n - 1; i = i + 2) {
if (arr[i] > arr[i + 1])
swap(arr, i, i + 1);
}
// If length is odd
if ((n & 1) > 0) {
for (int i = n - 1; i > 0; i = i - 2)
if (arr[i] > arr[i - 1])
swap(arr, i, i - 1);
}
}
// Driver Method
public static void main(String[] args)
{
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
System.out.println("Before rearranging");
System.out.println(Arrays.toString(arr));
Rearrange(arr, arr.length);
System.out.println("After rearranging");
System.out.println(Arrays.toString(arr));
}
}
/* This code is contributed by Mr. Somesh Awasthi */
Python3
# Python 3 program to rearrange array such
# that odd indexed elements are greater.
def rearrange(arr, n):
# Common code for odd and even lengths
for i in range(0, n - 1, 2):
if (arr[i] > arr[i + 1]):
temp = arr[i]
arr[i] = arr[i + 1]
arr[i + 1] = temp
# If length is odd
if (n & 1):
i = n - 1
while(i > 0):
if (arr[i] > arr[i - 1]):
temp = arr[i]
arr[i] = arr[i - 1]
arr[i - 1] = temp
i -= 2
# Utility that prints out an
# array on a line
def printArray(arr, size):
for i in range(0, size, 1):
print(arr[i], end = " ")
print("\n")
# Driver Code
if __name__ == '__main__':
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
n = len(arr)
print("Before rearranging")
printArray(arr, n)
rearrange(arr, n)
print("After rearranging")
printArray(arr, n)
# This code is contributed by
# Surendra_Gangwar
C#
// C# program to rearrange
// array such that odd
// indexed elements are
// greater.
using System;
class GFG
{
// Utility function to
// Swap two variables
public static void swap(int[] arr,
int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// method to rearrange
// array such that odd
// indexed elements are
// greater.
public static void Rearrange(int[] arr,
int n)
{
// Common code for odd
// and even lengths
for (int i = 0; i < n - 1; i = i + 2)
{
if (arr[i] > arr[i + 1])
swap(arr, i, i + 1);
}
// If length is odd
if ((n & 1) > 0)
{
for (int i = n - 1;
i > 0; i = i - 2)
if (arr[i] > arr[i - 1])
swap(arr, i, i - 1);
}
}
// Driver Code
static void Main()
{
int[] arr = {1, 2, 3, 4,
5, 6, 7, 8, 9};
Console.WriteLine("Before rearranging");
for(int i = 0; i < arr.Length; i++)
Console.Write(arr[i] + " ");
Rearrange(arr, arr.Length);
Console.WriteLine("\nAfter rearranging");
for(int i = 0; i < arr.Length; i++)
Console.Write(arr[i] + " ");
}
}
// This code is contributed
// by Sam007
PHP
<?php
// PHP program to rearrange array such that
// odd indexed elements are greater.
function rearrange(&$arr, $n)
{
// Common code for odd and even lengths
for ($i = 0; $i < $n - 1; $i = $i + 2)
{
if ($arr[$i] > $arr[$i + 1])
{
$temp = $arr[$i];
$arr[$i] = $arr[$i + 1];
$arr[$i + 1] = $temp;
}
}
// If length is odd
if ($n & 1)
{
for ($i = $n - 1; $i > 0; $i = $i - 2)
if ($arr[$i] > $arr[$i - 1])
{
$temp = $arr[$i];
$arr[$i] = $arr[$i - 1];
$arr[$i - 1] = $temp;
}
}
}
// Utility that prints out an array on a line
function printArray(&$arr, $size)
{
for ($i = 0; $i < $size; $i++)
echo $arr[$i] . " ";
echo "\n";
}
// Driver Code
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
$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 ita_c
?>
JavaScript
<script>
// Javascript program to rearrange array such that
// odd indexed elements are greater.
// Utility function to Swap two variables
function swap(arr,i,j)
{
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// method to rearrange array such that
// odd indexed elements are greater.
function Rearrange(arr,n)
{
// Common code for odd and even lengths
for (let i = 0; i < n - 1; i = i + 2) {
if (arr[i] > arr[i + 1])
swap(arr, i, i + 1);
}
// If length is odd
if ((n & 1) > 0) {
for (let i = n - 1; i > 0; i = i - 2)
if (arr[i] > arr[i - 1])
swap(arr, i, i - 1);
}
}
// Driver Method
let arr=[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
document.write("Before rearranging<br>");
for(let i=0;i<arr.length;i++)
{
document.write(arr[i]+" ");
}
document.write("<br>")
Rearrange(arr, arr.length);
document.write("After rearranging<br>");
for(let i=0;i<arr.length;i++)
{
document.write(arr[i]+" ");
}
// This code is contributed by avanitrachhadiya2155
</script>
OutputBefore rearranging
1 2 3 4 5 6 7 8 9
After rearranging
1 3 2 5 4 7 6 9 8
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Rearrange given Array such that each element raised to its index is odd
Given an array arr of length N, the task is to rearrange the elements of given array such that for each element, its bitwise XOR with its index is an odd value. If no rearrangement is possible return -1. Example: Input: arr[] = {1 2 4 3 5}Output: 1 2 3 4 5Explanation: In the above array:for 1st elem
13 min read
Rearrange array such that even positioned are greater than odd
Given an array arr[], sort the array according to the following relations: arr[i] >= arr[i - 1], if i is even, â 1 <= i < narr[i] <= arr[i - 1], if i is odd, â 1 <= i < nFind the resultant array.[consider 1-based indexing]Examples: Input: arr[] = [1, 2, 2, 1]Output: [1 2 1 2] Expla
9 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,
6 min read
Rearrange array such that even index elements are smaller and odd index elements are greater
Given an array, rearrange the array such that : If index i is even, arr[i] <= arr[i+1]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
10 min read
Modify Array such that no element is smaller/greater than half/double of its adjacent elements
Given an array, arr[] of size N. Find the minimum number of elements we need to insert between array elements such that the maximum element from two adjacent elements is not more than twice bigger than the minimum element i.e., max(arr[i], arr[i+1]) ? 2 * min(arr[i], arr[i+1]) where 0 ? i < N - 1
7 min read
Modify given array to make sum of odd and even indexed elements same
Given a binary array arr[] of size N, remove at most N/2 elements from the array such that the sum of elements at odd and even indices becomes equal. The task is to print the modified array.Note: N is always even. There can be more than one possible result, print any of them. Examples: Input: arr[]
10 min read
Reverse a subarray to maximize sum of even-indexed elements of given array
Given an array arr[], the task is to maximize the sum of even-indexed elements by reversing a subarray and print the maximum sum obtained. Examples: Input: arr[] = {1, 2, 1, 2, 1} Output: 5 Explanation: Sum of initial even-indexed elements = a[0] + a[2] + a[4] = 1 + 1 + 1 = 3 Reversing subarray {1,
9 min read
Rearrange an array such that product of every two consecutive elements is a multiple of 4
Given an array arr[] of size N, the task is to rearrange the array elements such that for every index i(1 <= i <= N - 1), the product of arr[i] and arr[i - 1] is a multiple of 4.Example: Input: arr[] = {1, 10, 100} Output: 1, 100, 10 Explanation: 1 * 100 is divisible by 4 100 * 10 is divisible
11 min read
Minimize swaps to rearrange array such that parity of index and corresponding element is same
Given an array A[], the task to find minimum swapping operations required to modify the given array A[] such that for every index in the array, parity(i) = parity(A[i]) where parity(x) = x % 2. If it's impossible to obtain such an arrangement, then print -1. Examples: Input: A[] = { 2, 4, 3, 1, 5, 6
6 min read
Rearrange Even and Odd Index Elements in K Operations
Given an array arr[] of size N (N is even) and a positive integer K, the task is to apply an operation to the array arr[] for K times. Applying the operation once will shift all the even indexed numbers to the beginning and all the odd indexed numbers to the end, maintaining their relative order. Ex
7 min read