Rearrange an array in maximum minimum form | Set 2 (O(1) extra space)

Given a sorted array of positive integers, rearrange the array alternately i.e first element should be the maximum value, second minimum value, third-second max, fourth-second min and so on.

Examples:

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

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

We have discussed a solution in below post:
Rearrange an array in maximum minimum form | Set 1 : The solution discussed here requires extra space, how to solve this problem with O(1) extra space.

In this post a solution that requires O(n) time and O(1) extra space is discussed. The idea is to use multiplication and modular trick to store two elements at an index.

even index : remaining maximum element.
odd index  : remaining minimum element.
 
max_index : Index of remaining maximum element
            (Moves from right to left)
min_index : Index of remaining minimum element
            (Moves from left to right)

Initialize: max_index = 'n-1'
            min_index = 0  
            max_element = arr[max_index] + 1 //can be any element which is more than the maximum value in array

For i = 0 to n-1            
    If 'i' is even
       arr[i] += arr[max_index] % max_element * max_element 
       max_index--     
    ELSE // if 'i' is odd
       arr[i] +=  arr[min_index] % max_element * max_element
       min_index++

How does expression “arr[i] += arr[max_index] % max_element * max_element” work ?
The purpose of this expression is to store two elements at index arr[i]. arr[max_index] is stored as multiplier and “arr[i]” is stored as remainder. For example in {1 2 3 4 5 6 7 8 9}, max_element is 10 and we store 91 at index 0. With 91, we can get original element as 91%10 and new element as 91/10.

Below implementation of above idea:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to rearrange an array in minimum
// maximum form
#include <bits/stdc++.h>
using namespace std;
  
// Prints max at first position, min at second position
// second max at third position, second min at fourth
// position and so on.
void rearrange(int arr[], int n)
{
    // initialize index of first minimum and first
    // maximum element
    int max_idx = n - 1, min_idx = 0;
  
    // store maximum element of array
    int max_elem = arr[n - 1] + 1;
  
    // traverse array elements
    for (int i = 0; i < n; i++) {
        // at even index : we have to put maximum element
        if (i % 2 == 0) {
            arr[i] += (arr[max_idx] % max_elem) * max_elem;
            max_idx--;
        }
  
        // at odd index : we have to put minimum element
        else {
            arr[i] += (arr[min_idx] % max_elem) * max_elem;
            min_idx++;
        }
    }
  
    // array elements back to it's original form
    for (int i = 0; i < n; i++)
        arr[i] = arr[i] / max_elem;
}
  
// Driver program to test above function
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    cout << "Original Arrayn";
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
  
    rearrange(arr, n);
  
    cout << "\nModified Array\n";
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to rearrange an
// array in minimum maximum form
  
public class Main {
  
    // Prints max at first position, min at second
    // position second max at third position, second
    // min at fourth position and so on.
    public static void rearrange(int arr[], int n)
    {
        // initialize index of first minimum and first
        // maximum element
        int max_idx = n - 1, min_idx = 0;
  
        // store maximum element of array
        int max_elem = arr[n - 1] + 1;
  
        // traverse array elements
        for (int i = 0; i < n; i++) {
            // at even index : we have to put
            // maximum element
            if (i % 2 == 0) {
                arr[i] += (arr[max_idx] % max_elem) * max_elem;
                max_idx--;
            }
  
            // at odd index : we have to put minimum element
            else {
                arr[i] += (arr[min_idx] % max_elem) * max_elem;
                min_idx++;
            }
        }
  
        // array elements back to it's original form
        for (int i = 0; i < n; i++)
            arr[i] = arr[i] / max_elem;
    }
  
    // Driver code
    public static void main(String args[])
    {
        int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        int n = arr.length;
  
        System.out.println("Original Array");
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
  
        rearrange(arr, n);
  
        System.out.print("\nModified Array\n");
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }
}
  
// This code is contributed by Swetank Modi

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to rearrange an 
# array in minimum maximum form
  
# Prints max at first position, min at second position
# second max at third position, second min at fourth
# position and so on.
def rearrange(arr, n):
  
    # Initialize index of first minimum 
    # and first maximum element
    max_idx = n - 1
    min_idx = 0
  
    # Store maximum element of array
    max_elem = arr[n-1] + 1
  
    # Traverse array elements
    for i in range(0, n) :
  
        # At even index : we have to put maximum element
        if i % 2 == 0 :
            arr[i] += (arr[max_idx] % max_elem ) * max_elem
            max_idx -= 1
  
        # At odd index : we have to put minimum element
        else :
            arr[i] += (arr[min_idx] % max_elem ) * max_elem
            min_idx += 1
  
    # array elements back to it's original form
    for i in range(0, n) :
        arr[i] = arr[i] / max_elem 
  
  
# Driver Code
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
n = len(arr)
  
print ("Original Array")
  
for i in range(0, n):
    print (arr[i], end = " ")
      
rearrange(arr, n)
  
print ("\nModified Array")
for i in range(0, n):
    print (int(arr[i]), end = " ")
      
# This code is contributed by Shreyanshi Arun.

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to rearrange an
// array in minimum maximum form
using System;
  
class main {
  
    // Prints max at first position, min at second
    // position, second max at third position, second
    // min at fourth position and so on.
    public static void rearrange(int[] arr, int n)
    {
        // initialize index of first minimum
        // and first maximum element
        int max_idx = n - 1, min_idx = 0;
  
        // store maximum element of array
        int max_elem = arr[n - 1] + 1;
  
        // traverse array elements
        for (int i = 0; i < n; i++) {
  
            // at even index : we have to put
            // maximum element
            if (i % 2 == 0) {
                arr[i] += (arr[max_idx] % max_elem) * max_elem;
                max_idx--;
            }
  
            // at odd index : we have to
            // put minimum element
            else {
                arr[i] += (arr[min_idx] % max_elem) * max_elem;
                min_idx++;
            }
        }
  
        // array elements back to it's original form
        for (int i = 0; i < n; i++)
            arr[i] = arr[i] / max_elem;
    }
  
    // Driver code
    public static void Main()
    {
        int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        int n = arr.Length;
        Console.WriteLine("Original Array");
        for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");
        Console.WriteLine();
  
        rearrange(arr, n);
  
        Console.WriteLine("Modified Array");
        for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");
    }
}
  
// This code is contributed by vt_m.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to rearrange an 
// array in minimum-maximum form
  
// Prints max at first position, 
// min at second position
// second max at third position, 
// second min at fourth
// position and so on.
function rearrange(&$arr, $n)
{
    // initialize index of first
    // minimum and first maximum element
    $max_idx = $n - 1; $min_idx = 0;
  
    // store maximum element of array
    $max_elem = $arr[$n - 1] + 1;
  
    // traverse array elements
    for ($i = 0; $i < $n; $i++)
    {
        // at even index : we have to
        // put maximum element
        if ($i % 2 == 0) 
        {
            $arr[$i] += ($arr[$max_idx] % 
                         $max_elem) * $max_elem;
            $max_idx--;
        }
  
        // at odd index : we have to 
        // put minimum element
        else
        {
            $arr[$i] += ($arr[$min_idx] % 
                         $max_elem) * $max_elem;
            $min_idx++;
        }
    }
  
    // array elements back to 
    // it's original form
    for ($i = 0; $i < $n; $i++)
        $arr[$i] = (int)($arr[$i] / $max_elem);
}
  
// Driver Code
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
$n = sizeof($arr);
  
echo "Original Array" . "\n";
for ($i = 0; $i < $n; $i++)
    echo $arr[$i] . " ";
  
rearrange($arr, $n);
  
echo "\nModified Array\n";
for ($i = 0; $i < $n; $i++)
    echo $arr[$i] . " ";
  
// This code is contributed
// by Akanksha Rai(Abby_akku)

chevron_right



Output :

Original Array
1 2 3 4 5 6 7 8 9 
Modified Array
9 1 8 2 7 3 6 4 5 

Thanks Saurabh Srivastava and Gaurav Ahirwar for suggesting this approach.

Another Approach: A simpler approach will be to observe indexing positioning of maximum elements and minimum elements. The even index stores maximum elements and the odd index stores the minimum elements. With every increasing index, the maximum element decreases by one and the minimum element increases by one. A simple traversal can be done and arr[] can be filled in again.

Note: This approach is only valid when elements of given sorted array are consecutive i.e., vary by one unit.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to rearrange an array in minimum
// maximum form
#include <bits/stdc++.h>
using namespace std;
  
// Prints max at first position, min at second position
// second max at third position, second min at fourth
// position and so on.
void rearrange(int arr[], int n)
{
    // initialize index of first minimum and first
    // maximum element
    int max_ele = arr[n - 1];
    int min_ele = arr[0];
    // traverse array elements
    for (int i = 0; i < n; i++) {
        // at even index : we have to put maximum element
        if (i % 2 == 0) {
            arr[i] = max_ele;
            max_ele -= 1;
        }
  
        // at odd index : we have to put minimum element
        else {
            arr[i] = min_ele;
            min_ele += 1;
        }
    }
}
  
// Driver program to test above function
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    cout << "Original Array\n";
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
  
    rearrange(arr, n);
  
    cout << "\nModified Array\n";
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to rearrange an
// array in minimum maximum form
  
public class Main {
  
    // Prints max at first position, min at second
    // position second max at third position, second
    // min at fourth position and so on.
    public static void rearrange(int arr[], int n)
    {
        // initialize index of first minimum and first
        // maximum element
        int max_ele = arr[n - 1];
        int min_ele = arr[0];
        // traverse array elements
        for (int i = 0; i < n; i++) {
            // at even index : we have to put maximum element
            if (i % 2 == 0) {
                arr[i] = max_ele;
                max_ele -= 1;
            }
  
            // at odd index : we have to put minimum element
            else {
                arr[i] = min_ele;
                min_ele += 1;
            }
        }
    }
  
    // Driver code
    public static void main(String args[])
    {
        int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        int n = arr.length;
  
        System.out.println("Original Array");
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
  
        rearrange(arr, n);
  
        System.out.print("\nModified Array\n");
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 program to rearrange an 
# array in minimum maximum form 
  
# Prints max at first position, min 
# at second position second max at
# third position, second min at 
# fourth position and so on. 
def rearrange(arr, n):
  
    # initialize index of first minimum 
    # and first maximum element 
    max_ele = arr[n - 1]
    min_ele = arr[0]
  
    # traverse array elements 
    for i in range(n):
          
        # at even index : we have to 
        # put maximum element
        if i % 2 == 0:
            arr[i] = max_ele
            max_ele -= 1
  
        # at odd index : we have to
        # put minimum element
        else:
            arr[i] = min_ele
            min_ele += 1
  
# Driver code
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
n = len(arr)
print("Origianl Array")
for i in range(n):
    print(arr[i], end = " ")
  
rearrange(arr, n)
print("\nModified Array")
for i in range(n):
    print(arr[i], end = " ")
  
# This code is contributed by Shrikant13 

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to rearrange 
// an array in minimum 
// maximum form
using System;
  
class GFG
{
    // Prints max at first 
    // position, min at second
    // position second max at
    // third position, second
    // min at fourth position
    // and so on.
    public static void rearrange(int []arr,
                                 int n)
    {
        // initialize index of 
        // first minimum and
        // first maximum element
        int max_ele = arr[n - 1];
        int min_ele = arr[0];
          
        // traverse array elements
        for (int i = 0; i < n; i++) 
        {
            // at even index : we have 
            // to put maximum element
            if (i % 2 == 0) 
            {
                arr[i] = max_ele;
                max_ele -= 1;
            }
  
            // at odd index : we have
            // to put minimum element
            else 
            {
                arr[i] = min_ele;
                min_ele += 1;
            }
        }
    }
  
    // Driver code
    static public void Main ()
    {
        int []arr = {1, 2, 3, 4, 
                     5, 6, 7, 8, 9};
        int n = arr.Length;
  
        Console.WriteLine("Original Array");
        for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");
  
        rearrange(arr, n);
  
        Console.Write("\nModified Array\n");
        for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");
    }
}
  
// This code is contributed by ajit

chevron_right



Output :

Original Array
1 2 3 4 5 6 7 8 9 
Modified Array
9 1 8 2 7 3 6 4 5 

Thanks Apollo Doley for suggesting this approach.

This article is contributed by Nishant Singh . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up