Shved
Shved

Reputation: 35

Sort only even numbers in array and do not touch odds

So I have an array of integers and the exercise tells me to sort only even elements. I understand this can be easily achieved by plain checking each element, which is probably O(n^2).
What I am trying to do is to write a comparator which takes only even numbers as parameters and then sort the whole array with it.

Comparator<Integer> comp = new Comparator<>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o1.compareTo(o2);
        }
    };
Arrays.sort(array, comp));

Is there any way to do so? Thank you

Upvotes: 0

Views: 1600

Answers (3)

Mr. Sai
Mr. Sai

Reputation: 13

Arrays.sort(array, (a, b) -> Integer.compare(a%2, b%2));

The above function sorts with custom comparison function which sorts only even numbers.

Upvotes: 0

Ashiwani Ranjan
Ashiwani Ranjan

Reputation: 11

public static void sortEven(int[] inputArray) {
    List list = new ArrayList();
    for (int i = 0; i < inputArray.length; i++) {
        if (inputArray[i]%2== 0)
            list.add(inputArray[i]);
    }
    Collections.sort(list);
    int j=0;
    for (int i = 0; i < inputArray.length; i++) {
        if (inputArray[i]%2== 0){
            inputArray[i] = Integer.parseInt(list.get(j).toString());
        j++;}
    }

    for (int i = 0; i < inputArray.length; i++) {
        System.out.println(inputArray[i]);
    }
}

Upvotes: 0

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37594

I would not try to create a Comparator like that. Seems more like hassle to achieve it. Instead you could split the array in odd and even numbers. Sort the even numbers and add the odd numbers to their previous position with ArrayList#add(index,number)

Upvotes: 1

Related Questions