Sort all even numbers in ascending order and then sort all odd numbers in descending order in a collection

This is an interview question.

There are some random numbers given (let's say in an integer array).

  1. How can we sort all the even numbers in ascending order first and then sort all the odd numbers in descending order.
  2. which Collection suits best.
Input numbers:
12 67 1 34 9 78 6 31
Output saved in Collection:
6 12 34 78 67 31 9 1 

Any collection that supports sorting with a custom comparer will do - even an array. Implement your custom comparator as follows:

public int compare(int x, int y) {
    if (x&1 == y&1) {
        // Both numbers are odd or both numbers are even
        if (x&1 == 0) {
            // Both numbers are even: compare as usual
            return Integer.compare(x, y);
        } else {
            // Both numbers are odd: compare in reverse
            return Integer.compare(y, x);
        }
    }
    // One is odd, the other one is even
    if (x&1 == 0) {
        return -1;
    }
    return 1;
}

Sort all even numbers in ascending order and odd numbers in , If both numbers are even: Compare both numbers, return -1 if first < second, 0 if equal, 1 if first > second (sorts even numbers ascending). If both numbers are odd: Compare both numbers, return 1 if first < second, 0 if equal, -1 if first > second (sorts odd numbers descending). If both numbers are even: Compare both numbers, return -1 if first < second, 0 if equal, 1 if first > second (sorts even numbers ascending). If both numbers are odd: Compare both numbers, return 1 if first < second, 0 if equal, -1 if first > second (sorts odd numbers descending).

You could do as follows

public ArrayList<Integer> sort(Integer[] input) {
        int length = input.length;
        ArrayList<Integer> oddNumber = new ArrayList<Integer>(0);
        ArrayList<Integer> evenNumber = new ArrayList<Integer>(0);
        for (int i = 0; i < length; i++) {
            Integer val = input[i];
            if(isEven(val)){
                evenNumber.add(val);
            } else {
                oddNumber.add(val);
            }
        }
        Collections.sort(evenNumber);
        Collections.sort(oddNumber, Collections.reverseOrder());

        evenNumber.addAll(oddNumber);

        return evenNumber;
    }

    public boolean isEven(Integer x) {
        return x % 2 == 0;
    }

EDIT

I implemented a comparator based on Jesper algorithm.

public ArrayList<Integer> sort(Integer[] input) {
        ArrayList<Integer> output = new ArrayList<Integer>(0);
        output.addAll(Arrays.asList(input));

        Collections.sort(output, new EvenOddComparator());

        return output;
    }

    public class EvenOddComparator implements Comparator<Integer>
    {
        final int BEFORE = -1;
        final int EQUAL = 0;
        final int AFTER = 1;

        @Override
        public int compare(Integer o1, Integer o2) {
            if (o1 % 2 == 0 && o2 % 2 != 0) {
                return BEFORE;
            } else if (o1 % 2 != 0 && o2 % 2 == 0) {
                return AFTER;
            } else if (o1 % 2 == 0 && o2 % 2 == 0) {
                return o1.compareTo(o2);
            } else if (o1 % 2 != 0 && o2 % 2 != 0) {
                return o2.compareTo(o1);
            }
            return EQUAL;
        }

    }

Cheers.

odd numbers appear first in ascending order followed by the even , at GeeksforGeeks Article: https://www.geeksforgeeks.org/sort-even-numbers- ascending Duration: 2:16 Posted: 13 Apr 2018 Collections.sort(list, (o1, o2) -> compareElements(o1, o2)); It does the same thing as the code above. It ensures that odd elements are always to the left of even elements, that odd elements are sorted in descending order, and that even elements are sorted in ascending order. share.

If it is not required that you implement the whole sorting algorithm yourself, you could just use Collections.sort(list, comparator), and you'll need to supply your own Comparator<Integer> implementation that compares the numbers and returns a result so that the numbers are sorted in the order that is defined by the rules.

The comparator would have to implement these rules:

  1. If first number is even and second number is odd, return -1 (because even numbers must come before odd numbers).
  2. If first number is odd and second number is even, return 1 (because even numbers must come before odd numbers).
  3. If both numbers are even: Compare both numbers, return -1 if first < second, 0 if equal, 1 if first > second (sorts even numbers ascending).
  4. If both numbers are odd: Compare both numbers, return 1 if first < second, 0 if equal, -1 if first > second (sorts odd numbers descending).

If you have the numbers in an array instead of a List, then use Arrays.sort(array, comparator).

Sort an array of integers into odd, then even, You already dug into the standard library a bit (which is good) and discovered the beautiful sort method. Using this method is a perfect start. i have to use std::sort() to sort numbers in an array like this: even numbers ascending and then odd numbers descending so far i got: #include <algorithm> #include &lt;iostream&gt;

Here's the code :

@Override
public int compare(Integer o1, Integer o2) {
    if (o1 % 2 ==0) 
    {
        if (o2 % 2 == 0)
        {
            if (o1 < o2)
                return -1;
            else
                return 1;
        }
        //if (o2 % 2 != 0)
        else
        {
            return -1;
        }
    }
    else 
    {
        if (o2 % 2 != 0)
        {
            if (o1 < o2)
                return 1;
            else
                return -1;
        }
        //if (o2 % 2 == 0)
        else
        {
            return 1;
        }
    }
}

How to sort elements in an array into order and even numbers and , Given an array of integers (both odd and even), sort them in such a way that the first part of the Duration: 2:16 Posted: 27 Jun 2019 The idea is simple. We create two auxiliary arrays evenArr[] and oddArr[] respectively. We traverse input array and put all even-placed elements in evenArr[] and odd placed elements in oddArr[]. Then we sort evenArr[] in ascending and oddArr[] in descending order. Finally copy evenArr[] and oddArr[] to get the required result.

package com.java.util.collection;

import java.util.Arrays;
import java.util.Collections;

public class EvenOddSorting {

    public static void eventOddSort(int[] arr) {
        int i =0;
        int j =arr.length-1;
        while(i<j) {
            if(isEven(arr[i]) && isOdd(arr[j])) {
                i++;
                j--;
            } else if(!isEven(arr[i]) && !isOdd(arr[j])) {
                swap(i,j,arr);
            } else if(isEven(arr[i])){
                i++;
            } else{
                j--;
            }

        }   
        display(arr);
        // even number sorting
        Arrays.sort(arr,0,i);
        insertionSort(arr,i,arr.length);
        // odd number sorting
        display(arr);

    }

    /**
     * Instead of insertion sort, you can use merge or quick sort.
     * @param arr
     * @param firstIndex
     * @param lastIndex
     */
    public static void insertionSort(int[] arr, int firstIndex, int lastIndex){
        for(int i=firstIndex+1;i<lastIndex;i++){
            int key =arr[i];
            int j=i-1;
            while(j>=firstIndex  && key > arr[j]) {
                arr[j+1] = arr[j];
                arr[j] =key;
                j=j-1;
            }
            System.out.println("\nAfter "+(i+1) +"  Iteration : ");
            display(arr);
        }
    }

    public static void display(int[] arr) {
        System.out.println("\n");
        for(int val:arr){
            System.out.print(val +"  ");
        }
    }

    private static void swap(int pos1, int pos2, int[] arr) {
        int temp = arr[pos1];
        arr[pos1]= arr[pos2];
        arr[pos2]= temp;
    }

    public static boolean isOdd(int i) {
        return (i & 1) != 0;
    }
    public static boolean isEven(int i) {
        return (i & 1) == 0;
    }
    public static void main(String[] args) {
        int arr[]={12, 67, 1, 34, 9, 78, 6, 31};
        eventOddSort(arr);
    }
}

Sort even and odd part of array, how to Sort all even numbers in ascending order and then sort all odd numbers in descending order in js A = [30, 19, 9, 15, 55, 24, 3, 78, 46,� Sort an Array – odd numbers appear first in ascending order followed by the even numbers in descending order. Objective: Given an array of intergers, sort it such that the odd numbers appear first followed by the even numbers . The odd numbers in ascending order and the even numbers in descending order. Input: An Array of Integers.

Sort an Array such that the odd numbers appear first followed by the even numbers . The odd numbers in ascending order and the even numbers in descending� Logic – Logic of this C program is that the one for loop is used to sort all the even elements from the array and print them. Similarly another for loop is used to sort all the odd elements and print them. Input – 10 12 55 23 11 Output – Odd numbers are – 55 23 11 Even numbers are – 10 12

Sort all even numbers in ascending order and then sort all odd , left and right and then sort all the odd numbers in descending order. which Collection suits� Consider we are sorting three numbers in ascending order. Steps: Start. Accept three numbers from user (a, b, c). If a < b then goto step 4 else goto step 8. If a < c then goto step 5 else goto step 7. If b < c then goto step 9 else goto step 6. Interchange b and c and goto step 9. Interchange a and c and goto step 3. Interchange a and b and

c++ program to sort an array in ascending and descending order Sort all even numbers in ascending order and then sort all odd numbers in descending You could use a group for sorting even and odd numbers and then sort by value with � Write a C program to input elements in an array from user and sort all even and odd elements of the given array separately without using any other array. If minimum element of the array is even then all even elements should be placed in sorted order before odd elements otherwise all odd elements should be placed first.

Comments
  • I'm not sure if this is a question you've been given (and are seeking answers to compare yours with) or if it's a question you plan to give. But either way, "incrementally" and "decrementally" don't mean what you're using them for. It should be "ascending" and "descending".
  • @Plutor: Thanks for shooting it out. I am average at English!. I have changed the title. Btw this is a question asked.
  • +1, fixed two typos. Method names should start with a lowercase and I changed "comparer" to "comparator" : )
  • You can't compare two integers by a - b - that won't work correctly in 25% of all cases assuming input over the whole range...
  • @Voo I replaced the hacker's version of the comparator with the call to the official Integer.compare() method. Thanks!
  • Its worth noting that -1 % 2 == -1 and 1 % 2 == 1 i.e. n % 2 has three possible results. A simple fix is to use (x & 1) == (y & 1) or ((x ^ y) & 1) == 0
  • @PeterLawrey Thanks! In my own code I use bit ops to check if a number is odd or even. I decided to go for a bit more expressive code with the remainder operator, and got it wrong :)
  • The list oddNumber was never sorted. Ass the even number should be first there is no need to create another list, we can just add all that list. In addition we know that size of the result so there is no need to use 0 as begin size of ArrayList. Concluding the algorithm you have presented is not the best choice for an interview answer.
  • Your welcome, but better then a sort method, you should use a Comparator implementation and focus on the algorithm. Please look at Jesper answer and try to implement that logic.
  • Well, there's another version of the algorithm based on Jesper anwser ;)
  • That is better but the else is not required and the last return as EQUAL look like abnormal.