Java – how do I move all even numbers to the front of an array?

Here are the questions –

Given an array of integers as input, returns an array containing the same numbers as the input array, but rearranges so that all even numbers come first and odds follow Note that the order of even and odd numbers should be maintained, that is, if the even number N1 before the even number N2 appears in the input, it should appear before N2 in the output array N1 The same is true of odd numbers Also note that you should not create any new arrays in this issue

The work done so far is as follows, but I can't get the expected output

public class MoveEvenToFront {

    static int[] testcase1 = {3,5,4,6,8,9,7,10};

    public static void main(String[] args) {

        MoveEvenToFront testInstance = new MoveEvenToFront();
        int[] result = testInstance.moveEvenToFront(testcase1);
        System.out.print("{");

        for (int i = 0; i < result.length; i++) {
            if (i > 0) {
                System.out.print(",");
            }
            System.out.print(result[i]);
        }
        System.out.print("}");
    }

    public int[] moveEvenToFront(int[] arr) {
        int temp = 0;

        for (int i = 1; i < arr.length; i++) {
            if (arr[i - 1] % 2 != 0) {
                temp = arr[i - 1];
                arr[i - 1] = arr[i];
                arr[i] = temp;
            }
        }
        return arr;
    }
}

The expected output of test case {1,2,3,10,12} is {2,12,1,7}

Solution

Your algorithm is wrong You are checking for uneven arr [I-1] and swapping with arr [i] If arr [i] is also an odd number, you do not check it, even if it is an odd number, it will move to the front

What you can do is

>Find the first even number in the array, exchange it with the first index and increment the index. > Then find the second even number and swap it with the second index until the end of the array

The change method is as follows:

public int[] moveEvenToFront(int[] arr){
    int temp=0;
    int a=0;
    for(int i=0;i<arr.length;i++){
        if(arr[i]%2==0){

            for (int j=i;j>a;j--){
                temp=arr[j-1];
                arr[j-1]=arr[j];
                arr[j]=temp;
            }
            a++;
        }
    }
    return arr;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>