Pair the array BigSmall:



 

 

Looking for a best optimal solution.

Two different style is possible 

1.Sort the array and  use Two pointer

2. Sort in different index.(Best)

 

 

 

 

 

 

 

 

 

 import java.util.*;
class PairBigSmall{
    public static void main(String[] args) 
    {
        
        int[]arr={8,9,1,2,7,3,4};
        System.out.println(Arrays.toString(arr));
        
        for (int i = 0; i < arr.length; i++)
        {
            if (i % 2 == 0)
            {
                for (int j = i; j < arr.length; j++)
                {
                    if (arr[i] < arr[j])
                    {
                        int temp = arr[i];
                        arr[i] = arr[j];
                        arr[j] = temp;
                    }
                }
            }
            else {
                for (int j = i; j < arr.length; j++)
                {
                    if (arr[i] > arr[j])
                    {
                        int temp = arr[i];
                        arr[i] = arr[j];
                        arr[j] = temp;
                    }
                }
            }
        }
        System.out.println(Arrays.toString(arr));
    }
}


Comments

Popular posts from this blog

Strings

Arrays