+ 2

is there any better way to solve this problem?

Write a Java program to rearrange all the elements of an given array of integers so that all the odd numbers come before all the even numbers. import java.util.Arrays; public class Arr_arrange { public static void main(String[] args) { int[] arr = {12,76,89,54,23,93,19}; int[] na = new int[arr.length]; int j = 0; for (int k : arr) { if (k % 2 != 0) { na[j] = k; j++; } } for (int k : arr) { if (k % 2 == 0) { na[j] = k; j++; } } System.out.println("new arrays is : " + Arrays.toString(na)); } } OUTPUT : new arrays is : [89, 23, 93, 19, 12, 76, 54]

12th Jun 2022, 5:59 AM
Shashi Singh
Shashi Singh - avatar
4 odpowiedzi
+ 3
Not better, just another way into doing it. https://code.sololearn.com/cWpPQznnL49H/?ref=app
12th Jun 2022, 6:46 AM
Ipang
+ 3
Using the Comparator functional interface. https://code.sololearn.com/cVvhWS5mRX9I/?ref=app Sadly the array must be boxed for this to work (won't run on primitive int) so it's a little tricky. If it's an array of objects, the comparator can be also passed directly to Arrays.sort() without creating a separate stream.
12th Jun 2022, 2:34 PM
Tibor Santa
Tibor Santa - avatar
+ 3
Like Tibor Santa, using stream and comparator but a bit more condensed 😉 https://code.sololearn.com/cVW1GLhWpaLe/?ref=app
12th Jun 2022, 8:45 PM
Roland
Roland - avatar
+ 2
public static int[] sortOddFirst( int[] a) { int iOdd=0, iEven = a.length-1; int[] aNew = new int[a.length]; for (int n: a) if ( (n & 1) == 0) aNew[iEven--] = n; else aNew[iOdd++ ] = n; return aNew; }
12th Jun 2022, 3:23 PM
zemiak