Rearrange a given array of int values so that the even numbers appear first, followed by the odd numbers.
Here is an example of how you might implement the orderEvenBeforeOdd method in Java:
class ArrayUtils { public static void orderEvenBeforeOdd(int[] array) { int i = 0; int j = array.length - 1; while (i < j) { if (array[i] % 2 == 0) { i++; } else if (array[j] % 2 == 1) { j--; } else { int temp = array[i]; array[i] = array[j]; array[j] = temp; i++; j--; } } }}
You can then use the orderEvenBeforeOdd method as follows:
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9};ArrayUtils.orderEvenBeforeOdd(array);System.out.println(Arrays.toString(array)); // Outputs [2, 4, 6, 8, 1, 3, 5, 7, 9]
class ArrayUtils {
public static void orderEvenBeforeOdd(int[] array) {
int i = 0;
int j = array.length - 1;
while (i < j) {
if (array[i] % 2 == 0) {
i++;
} else if (array[j] % 2 == 1) {
j--;
} else {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
}
}
}
You can then use the orderEvenBeforeOdd method as follows:
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9};
ArrayUtils.orderEvenBeforeOdd(array);
System.out.println(Arrays.toString(array)); // Outputs [2, 4, 6, 8, 1, 3, 5, 7, 9]
0 Comments
if you are not getting it then ask i am glad to help