Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I move all even numbers to front in an array?

Tags:

java

arrays

Following is the problem-

Given an array of integers as input, return an array that contains the same numbers as that in the input array, but rearranged so that all the even numbers are in front and the odds numbers are at the back. Note that the order of the even numbers and odd numbers should be maintained i.e. if an even number n1 that appears before an even number n2 in the input, then in the output array n1 should appear before n2. The same is true for odd numbers. Also note that in this problem you should not create any new array.

What is done so far is as follows but I am unable to 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 for testcase {1,2,3,4,5,6,7,8,10,12} is {2,4,6,8,10,12,1,3,5,7}.

like image 270
IT_Philic Avatar asked Sep 03 '25 17:09

IT_Philic


1 Answers

Your algorithm is wrong. You are checking if arr[i-1] is not even and swapping it with arr[i]. If arr[i] is also odd, then you are not checking for it, and it moves to the front even when it is odd.

What you could do is

  • find the first even number in the array and swap it with first index and increment the index.
  • then find the second even number and swap it with second index, continue until end of array.

change the method as shown below:

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;
}
like image 192
anirudh Avatar answered Sep 06 '25 14:09

anirudh