I am attempting to sort an array of integers such that all even numbers precede odd numbers, without using any external libraries. You may recognize this from: http://codingbat.com/prob/p105771
" Return an array that 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 may modify and return the given array, or make a new array. " I have code that accomplishes this goal:
public int[] evenOdd(int[] nums) {
int c=0;
int c2=0;
int [] nums2=new int[nums.length];
for(int i=0;i<nums.length;i++)
{
if(nums[i]%2==0)
{
nums2[c]=nums[i];
c++;
}
else
{
nums2[nums.length-c2-1]=nums[i];
c2++;
}
}
return nums2;
}
I have also approached the problem by calling array.sort()
and then inserting the numbers by index, incrementing by two, then inserting the remainder. This also works.
So, to make a long post short-is there a more elegant way to accomplish this goal in future? Thanks!