I need elements of matrix put into an array, then i need to sort first odd numbers and then even numbers Example: This is array: 5, 9, 1, 2, 3, 8, 4. output: 1,3,5,9 ; 2,4,8
This is my code:
int[] array=new int[mat.length*mat[0].length];
int cnt=0;
for(int i=0; i<mat.length; i++)
{
for(int j=0; j<mat[0].length; j++)
{
array[cnt]=mat[i][j];
cnt++;
}
}
int cnt1=0;
int cnt2=0;
int[] array1=new int[array.length];
int[] array2=new int[array.length];
for(int i=0; i<array.length; i++)
{
if(array[i]%2==0)
{
array1[br1]=array[i];
cnt1++;
}
else
{
array2[br2]=array[i];
cnt2++;
}
}
The problem is this two arrays for odd and even numbers, because i don't know their length and if i put the size of whole array, then i will get zeros for remaining places in odd array for number that is even and vice versa. How would you do this? Thank you
If you can use List you can do
List<Integer> even = new ArrayList<>();
List<Integer> odd = new ArrayList<>();
for(int i=0; i<mat.length; i++) {
for(int j=0; j<mat[0].length; j++) {
if (mat[i][j] % 2 == 0)
even.add(mat[i][j]);
else
odd.add(mat[i][j]);
}
}
Collections.sort(even);
Collections.sort(odd);
odd.addAll(even);
for (int v: odd){
System.out.println(v);
}
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