I have an array where I have some numbers. Now I want to sort even numbers in a separate array and odd numbers in a separate. Is there any API to do that? I tried like this
int[] array_sort={5,12,3,21,8,7,19,102,201};
int [] even_sort;
int i;
for(i=0;i<8;i++)
{
if(array_sort[i]%2==0)
{
even_sort=Arrays.sort(array_sort[i]);//error in sort
System.out.println(even_sort);
}
}
If you want the odd and even numbers in an array, you need to check it with each element in the for loop itself. We know that if the last digit is divisible by 2 then it is an even else it is an odd.
For printing the even numbers in the array, run a loop from 0 to n and in each loop check if arr[i] %2 = 0 or not. If it is equal to 0 print it under even numbers. 4. For printing the odd numbers in the array, run a loop from 0 to n and in each loop check if arr[i] %2 = 1 or not.
Plain and simple.
int[] array_sort = {5, 12, 3, 21, 8, 7, 19, 102, 201 };
List<Integer> odd = new ArrayList<Integer>();
List<Integer> even = new ArrayList<Integer>();
for (int i : array_sort) {
if ((i & 1) == 1) {
odd.add(i);
} else {
even.add(i);
}
}
Collections.sort(odd);
Collections.sort(even);
System.out.println("Odd:" + odd);
System.out.println("Even:" + even);
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