Open In App

Java Program For Rearranging An Array In Maximum Minimum Form – Set 2 (O(1) extra space)

Improve
Improve
Like Article
Like
Save
Share
Report

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  

            // can be any element which is more 
            // than the maximum value in array
            max_element = arr[max_index] + 1 

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

    // if 'i' is odd   
    ELSE 
       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:

Java




// 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(
        "Modified Array");
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }
}
// This code is contributed by Swetank Modi


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), as we are using a loop to traverse N times.

Auxiliary Space: O(1), as we are not using any extra space.

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:

Java




// 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(
        "Modified Array");
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }
}


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), as we are using a loop to traverse N times.

Auxiliary Space: O(1), as we are not using any extra space.

Please refer complete article on Rearrange an array in maximum minimum form | Set 2 (O(1) extra space) for more details!



Last Updated : 31 May, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads