Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array even & odd sorting

Tags:

java

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);
}
}
like image 658
Sumithra Avatar asked Oct 14 '10 07:10

Sumithra


People also ask

How do you determine if an array is even or odd?

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.

How do I print an even array?

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.


1 Answers

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);
like image 110
BjornS Avatar answered Nov 09 '22 20:11

BjornS