Rearrange sorted array such that all odd indices elements comes before all even indices element - GeeksforGeeks

16 Dec, 2021
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 by modifying the given array by taking the value (maximum array element + 1) as the pivot(say) and then for the first half of the array add the value (arr[oddIndex]%pivot)*pivot at the odd indices oddIndex and for the second half of the array add the value (arr[evenIndex]%pivot)*pivot at the even indices evenIndex. After the above steps, divide each array element by the value of pivot. Below is the illustration for the same:
Consider the array arr[] = {3, 7}, then the value of pivot is 7 + 1 = 8.
For the first half:Modify the array element arr[0] = 3 + (7%8)*8 = 3+ 56 = 59.
For the second half:
Modify the array element arr[1] = 7 + (59%8)*8 = 7 + 24 = 31.
Dividing each array element by the pivot  modifies the array to {7, 3} which is the required result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to print the arrayvoid printTheArray(int arr[], int N){  for (int i = 0; i < N; i++)    cout << arr[i] << " ";} // Function to rearrange the array such// that odd indexed elements come before// even indexed elementsvoid rearrange(int arr[], int N){  //Reduces the size of array by one  //because last element does not need  //to be changed in case N = odd  if (N & 1)    N--;   // Initialize the variables  int odd_idx = 1, even_idx = 0;   int i, max_elem = arr[N - 1] + 1;   // Iterate over the range  for (i = 0; i < N / 2; i++) {     // Add the modified element at    // the odd position    arr[i] += (arr[odd_idx] % max_elem) * max_elem;     odd_idx += 2;  }   // Iterate over the range  for (; i < N; i++) {     // Add the modified element at    // the even position    arr[i] += (arr[even_idx] % max_elem) * max_elem;     even_idx += 2;  }   // Iterate over the range  for (int i = 0; i < N; i++) {     // Divide by the maximum element    arr[i] = arr[i] / max_elem;  }} // Driver Codeint main(){  int arr[] = { 1, 2, 3, 4, 5, 16, 18, 19 };  int N = sizeof(arr) / sizeof(arr[0]);     rearrange(arr, N);  printTheArray(arr, N);   return 0;} //This code is contributed by Akash Jha
// Java program for the above approachimport java.io.*; class GFG{ // Function to print the arraystatic void printTheArray(int arr[], int N){  for (int i = 0; i < N; i++)   System.out.print(arr[i] + " ");} // Function to rearrange the array such// that odd indexed elements come before// even indexed elementsstatic void rearrange(int arr[], int N){     // Reduces the size of array by one  // because last element does not need  // to be changed in case N = odd  if ((N & 1) != 0)    N--;   // Initialize the variables  int odd_idx = 1, even_idx = 0;   int i, max_elem = arr[N - 1] + 1;   // Iterate over the range  for (i = 0; i < N / 2; i++) {     // Add the modified element at    // the odd position    arr[i] += (arr[odd_idx] % max_elem) * max_elem;     odd_idx += 2;  }   // Iterate over the range  for (; i < N; i++) {     // Add the modified element at    // the even position    arr[i] += (arr[even_idx] % max_elem) * max_elem;     even_idx += 2;  }   // Iterate over the range  for (i = 0; i < N; i++) {     // Divide by the maximum element    arr[i] = arr[i] / max_elem;  }} // Driver Codepublic static void main (String[] args){     int arr[] = { 1, 2, 3, 4, 5, 16, 18, 19 };    int N = arr.length;       rearrange(arr, N);    printTheArray(arr, N); }} // This code is contributed by avijitmondal1998.
# Python program for the above approach # Function to print the arraydef printArray(arr, n):  for i in range(N):    print(arr[i],end=" ")  print("\n")  # Function to rearrange the array such# that odd indexed elements come before# even indexed elementsdef rearrange(arr, N):     #Reduces the size of array by one  #because last element does not need  #to be changed in case N = odd  if (N & 1):    N-=1   # Initialize the variables  odd_idx = 1  even_idx = 0  max_elem = arr[N - 1] + 1   # Iterate over the range  for i in range(N//2):     # Add the modified element at    # the odd position    arr[i] += (arr[odd_idx] % max_elem) * max_elem    odd_idx += 2      # Iterate over the range  for i in range(N//2,N):     # Add the modified element at    # the even position    arr[i] += (arr[even_idx] % max_elem) * max_elem    even_idx += 2      # Iterate over the range  for i in range(N):     # Divide by the maximum element    arr[i] = arr[i] // max_elem      # Driver Codeif __name__=="__main__":     arr = [ 1, 2, 3, 4, 5, 16, 18, 19 ]  N = len(arr)     rearrange(arr, N)  printArray(arr, N); #This code is contributed by Akash Jha
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to print the arraystatic void printTheArray(int []arr, int N){  for (int i = 0; i < N; i++)    Console.Write(arr[i]+" ");} // Function to rearrange the array such// that odd indexed elements come before// even indexed elementsstatic void rearrange(int []arr, int N){  // Reduces the size of array by one  // because last element does not need  // to be changed in case N = odd  if ((N & 1) != 0)    N--;   // Initialize the variables  int odd_idx = 1, even_idx = 0;   int i, max_elem = arr[N - 1] + 1;   // Iterate over the range  for (i = 0; i < N / 2; i++) {     // Add the modified element at    // the odd position    arr[i] += (arr[odd_idx] % max_elem) * max_elem;     odd_idx += 2;  }   // Iterate over the range  for (; i < N; i++) {     // Add the modified element at    // the even position    arr[i] += (arr[even_idx] % max_elem) * max_elem;     even_idx += 2;  }   // Iterate over the range  for(i = 0; i < N; i++) {     // Divide by the maximum element    arr[i] = arr[i] / max_elem;  }} // Driver Codepublic static void Main(){  int []arr = { 1, 2, 3, 4, 5, 16, 18, 19};  int N = arr.Length;     rearrange(arr, N);  printTheArray(arr, N);}} // This code is contributed by SURENDRA_GANGWAR.
<script>// Javascript program for the above approach // Function to print the arrayfunction printTheArray(arr, N){  for (let i = 0; i < N; i++)    document.write(Math.floor(arr[i]) + " ");} // Function to rearrange the array such// that odd indexed elements come before// even indexed elementsfunction rearrange(arr, N){  // Reduces the size of array by one  // because last element does not need  // to be changed in case N = odd  if (N & 1)    N--;   // Initialize the variables  let odd_idx = 1, even_idx = 0;   let i, max_elem = arr[N - 1] + 1;   // Iterate over the range  for (i = 0; i < N / 2; i++) {     // Add the modified element at    // the odd position    arr[i] += (arr[odd_idx] % max_elem) * max_elem;     odd_idx += 2;  }   // Iterate over the range  for (; i < N; i++) {     // Add the modified element at    // the even position    arr[i] += (arr[even_idx] % max_elem) * max_elem;     even_idx += 2;  }   // Iterate over the range  for (let i = 0; i < N; i++) {     // Divide by the maximum element    arr[i] = arr[i] / max_elem;  }} // Driver Code  let arr =[ 1, 2, 3, 4, 5, 16, 18, 19 ];  let N = arr.length;     rearrange(arr, N);  printTheArray(arr, N); // This code is contributed by _saurabh_jaiswal.</script>
2 4 16 19 1 3 5 18
 
Time Complexity: O(N)Auxiliary Space: O(1)
akashjha2671
avijitmondal1998
SURENDRA_GANGWAR
_saurabh_jaiswal
anikakapoor
array-rearrange
Blogathon-2021
Arrays
Blogathon
Greedy
Mathematical
Arrays
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Count pairs with given sum
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
How to Call or Consume External API in Spring Boot?
How to Create a Table With Multiple Foreign Keys in SQL?
Re-rendering Components in ReactJS
Python NOT EQUAL operator
SQL Query to Insert Multiple Rows