Rearrange Array such that adjoining distinction is odd


  

import java.io.*;

import java.lang.*;

import java.util.*;

  

class GFG {

  

    

    static void rearrange(int arr[], int n)

    {

  

        

        ArrayList<Integer> odd_ele = new ArrayList<>();

  

        

        ArrayList<Integer> even_ele = new ArrayList<>();

  

        

        int odd = ;

  

        

        int even = ;

  

        

        

        

        for (int i = ; i < n; i++) {

  

            if ((arr[i] & 1) == 1) {

                odd_ele.add(arr[i]);

                odd++;

            }

            else {

                even_ele.add(arr[i]);

                even++;

            }

        }

  

        

        if (n % 2 == ) {

  

            

            

            

            

            if (odd == (n / 2) && even == (n / 2)) {

                for (int i = ; i < odd_ele.measurement(); i++) {

                    System.out.print(odd_ele.get(i) + " "

                                     + even_ele.get(i)

                                     + " ");

                }

            }

            else {

                System.out.println(-1);

            }

        }

  

        

        else if (n % 2 != ) {

  

            

            

            

            

            if (even == ((n / 2) + 1)

                || odd == ((n / 2) + 1)) {

                if (even == ((n / 2) + 1)) {

                    System.out.print(

                        even_ele.get(even_ele.measurement() - 1)

                        + " ");

                    for (int i = ; i < odd_ele.measurement();

                         i++) {

                        System.out.print(

                            odd_ele.get(i) + " "

                            + even_ele.get(i) + " ");

                    }

                }

                else {

  

                    for (int i = ; i < even_ele.measurement();

                         i++) {

                        System.out.print(

                            odd_ele.get(i) + " "

                            + even_ele.get(i) + " ");

                    }

                    System.out.print(

                        odd_ele.get(odd_ele.measurement() - 1));

                }

            }

            else {

                System.out.println(-1);

            }

        }

        System.out.println();

    }

  

    

    public static void predominant(String[] args)

        throws java.lang.Exception

    {

        int[] arr = { 6, 1, 3, 4, 5, 2 };

        int N = arr.size;

  

        

        rearrange(arr, N);

    }

}

See also  High 5 Programming Languages For Moral Hackers

Leave a Reply