Sunday, October 30, 2022
HomeWordPress DevelopmentRearrange Array such that adjoining distinction is odd

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 = 0;

  

        

        int even = 0;

  

        

        

        

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

  

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

                odd_ele.add(arr[i]);

                odd++;

            }

            else {

                even_ele.add(arr[i]);

                even++;

            }

        }

  

        

        if (n % 2 == 0) {

  

            

            

            

            

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

                for (int i = 0; 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 != 0) {

  

            

            

            

            

            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 = 0; i < odd_ele.measurement();

                         i++) {

                        System.out.print(

                            odd_ele.get(i) + " "

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

                    }

                }

                else {

  

                    for (int i = 0; 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 important(String[] args)

        throws java.lang.Exception

    {

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

        int N = arr.size;

  

        

        rearrange(arr, N);

    }

}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments