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}
.
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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With