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

15 Jun, 2022
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++
Java
Python3
C#
PHP
Javascript
// 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 functionint 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;}
// 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
# 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 Codearr = [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.
// C# program to rearrange an// array in minimum maximum formusing 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.
<?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)
<script> // JavaScript 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    let max_idx = n - 1, min_idx = 0;     // store maximum element of array    let max_elem = arr[n - 1] + 1;     // traverse array elements    for (let 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 (let i = 0; i < n; i++)        arr[i] = Math.floor(arr[i] / max_elem);} // Driver program to test above function     let arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ];    let n = arr.length;     document.write("Original Array<br>");    for (let i = 0; i < n; i++)        document.write(arr[i] + " ");     rearrange(arr, n);     document.write("<br>Modified Array<br>");    for (let i = 0; i < n; i++)        document.write(arr[i] + " "); // This code is contributed by Surbhi Tyagi. </script>
Output : 
Original Array
1 2 3 4 5 6 7 8 9 
Modified Array
9 1 8 2 7 3 6 4 5 
Time Complexity: O(n)
Auxiliary Space: O(1), as no extra space is used
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++
Java
Python3
C#
Javascript
// 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 functionint 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;}
// 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] + " ");    }}
# 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 codearr = [1, 2, 3, 4, 5, 6, 7, 8, 9]n = len(arr)print("Original 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
// C# program to rearrange// an array in minimum// maximum formusing 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
<script> // Javascript 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        let max_ele = arr[n - 1];        let min_ele = arr[0];        // traverse array elements        for (let 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     let arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ];    let n = arr.length;     document.write("Original Array" + "<br />");    for (let i = 0; i < n; i++)        document.write(arr[i] + " ");    document.write("<br />");         rearrange(arr, n);     document.write("\nModified Array\n" + "<br />");    for (let i = 0; i < n; i++)       document.write(arr[i] + " "); </script>
Output : 
Original Array
1 2 3 4 5 6 7 8 9 
Modified Array
9 1 8 2 7 3 6 4 5 
Time Complexity: O(n)
Auxiliary Space: O(1), as no extra space is used
Thanks Apollo Doley for suggesting this approach.  
Rearrange an array in Max & Min Form | DSA | Programming Tutorials | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersRearrange an array in Max & Min Form | DSA | Programming Tutorials | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 16:46•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=oK0FKG5kigo" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Aarti_Rathi Nishant Singh . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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. 
jit_t
AmanRanjanVerma
shrikanth13
Akanksha_Rai
DEVENDERSINGH
surbhityagi15
code_hunt
anikakapoor
_shinchancode
array-rearrange
Modular Arithmetic
Zoho
Arrays
Sorting
Zoho
Arrays
Sorting
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.