Given an array of integers nums, half of the integers in nums are odd, and the other half are even. Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even. Return any answer array that satisfies this condition.
I've written this code.
public static void main(String[] args) {
int[] nums = {1,3,5,7,2,4,6,8};
int[] res = new int[nums.length];
int a=0;
int b=0;
int c=1;
while (a < nums.length && b < nums.length+1 && c < nums.length+1){
if (nums[a]%2 == 0){
res[b] = nums[a];
a++;
b += 2;
}
if (nums[a]%2 != 0){
res[c] = nums[a];
a++;
c += 2;
}
}
for (int i : res){
System.out.println(res[i]);
}
System.out.println();
}
While executing the {1,3,5,7,2,4,6,8} in even spaces it fills '0' but, while executing the {2,4,6,8,10,1,3,5,7,9} it gives correct answer. Can someone please help me here?
Because it in the first case, your code puts the odd numbers in the
resarray, and then stops because of thec < nums.length+1condition. You only needa < nums.lengthaswhilecondition.