Reputation: 1
Modify the parameter array so it still contains the exact same numbers as the given array, but rearranged so that all the even numbers come before all the odd numbers. Other than that, the numbers can be in any order. You must modify the array arguments by changing array in method evensLeft. The array may be empty or have only one element. In both cases, no change should be made.
public void evensLeft(int[] array){
int j = array.length-1;
int h = 0;
int[] newArray=array;
for (int k = 0; k < newArray.length; k++) {
if(newArray[k]%2==0){
array[h]=newArray[k];
h++;
}else{
array[j]=newArray[k];
j--;
}
}
}
My tests aren't passing and i can't seem to figure out what is wrong.
Upvotes: 0
Views: 543
Reputation: 8975
I tried something using Comparator.
Set<Integer> ts=new TreeSet<Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if(o1%2==0){
if(o2%2==0){
return -1;
}
return -1;
}else if(o2%2==0){
return 1;
}
return 1;
}
});
ts.addAll(Arrays.asList(new Integer[]{2,1,5,7,8,3}));
System.out.println(ts);
Output:
[8, 2, 1, 5, 7, 3]
Upvotes: 0
Reputation: 7735
Copying link to the array, has no meaning, since you will still be modifying original array
int[] newArray=array;
use
java.util.Arrays.copyOf(array, array.length)
Upvotes: 0
Reputation: 1306
The problem is with the line int[] newArray=array;
You should copy array
to newArray
but int[] newArray=array;
is simply making newArray
to reference an array of integers that array
is referencing.
Change your code to int[] newArray=array.clone();
to copy the integer array, then it should work.
Upvotes: 1