Rearrange Array in Maximum-Minimum form

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.

Naive Solution:



Here we will use an auxiliary array to store the elements in correct order. For even indices of the array  Large numbers from the given array are added. For odd indices small numbers are added.

Code:

import java.util.*;

public class Test{
    
  public static void main(String[] args) {
    
    Scanner in = new Scanner(System.in);
    int[] a = {1,2,3,4,5,6,7,8,9};
    int n = a.length;
    int[] temp = new int[n];
    int small = 0;
    int large = n-1;
    for(int i=0; i<n; i++){
        if(i%2 == 0){
            temp[i] = a[large--];
        }
        else{
            temp[i] = a[small++];
        }
        
    }
    for(int i=0; i<n; i++){
        System.out.print(temp[i]+" ");
    }
      
    
  }
}

Efficient Solution:

We can solve the same problem without using extra space. We exploit the properties of modulus operator here.

Consider an array 1,2,3,4,5 

    The maximum element here is 5. When we increment the maximum element by 1 we get 6.
    So if we apply mod 6 with all elements in the array, we will get the original elements.(They wont change, as we selected 6 which is greater than all the array elements.
   The main characteristic is even if we add multiples of 6 to the array elements, we can get back the original values in the array, by applying the modulus operator .

     Lets take a[0], We have to place 5 here.(Since 5 is the first maximum)
         We multiply 5 and 6 which is 30. We add 30 to a[0]. So a[0] becomes 31. 
         Here is the trick, when we apply mod 6 we get back the original element 1. And when we apply divide by 6 we get back the rearranged element 5.

Code:

import java.util.*;

public class Test{
    
  public static void main(String[] args) {
    
    Scanner in = new Scanner(System.in);
    int[] a = {1,2,3,4,5,6,7,8,9};
    int n = a.length;
    int small = 0;
    int large = n-1;
    int maximum = a[n-1]+1;
    for(int i=0; i<n; i++){
        if(i%2 == 0){
            a[i] += (a[large]% maximum) * maximum;
            large--;
        }
        else{
            a[i] += (a[small]%maximum) * maximum;
            small++;
        }
        
    }
    for(int i=0; i<n; i++){
        a[i] /= maximum;
        System.out.print(a[i]+" ");
    }
      
    
  }
}


Output:

9 1 8 2 7 3 6 4 5 
















Comments

Popular posts from this blog

Second Largest Element

Reverse words in a given string