Respuesta :
Answer:
I am writing a JAVA program.
public class EvenOdd
// function that rearranges array elements so that even values come before odd values
{ static void evenBeforeOdd (int array[]) {
/* i and j are two array indices and i is positioned at the start of the array and j is positioned at last element of array */
int i = 0, j = array.length - 1;
while (i < j) { // loop continues till value of i is less than that of j
while (array[i]%2 == 0 && i < j) //array element at i is even no.
i = i + 1; // increments index i by one
while (array[j]%2 == 1 && i < j) // array element at j-th position is odd
j = j - 1; //decrements j index by 1
if (i < j) { if i is less than j swap their elements
int temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--; } } }
public static void main (String[] args)
{ int array[] = {5, 4, 2, 11, 9, 10, 7, 3};
// declares an array and assign it values
evenBeforeOdd(array); // calls evenBeforeOdd() function
for (int i = 0; i < array.length; i++)
//traverses through array using loop to print elements of the array with even elements before odd
System.out.print(array[i]+"\n"); } }
Explanation:
- This program has a method evenBeforeOdd() that takes an array of integers as parameter and rearranges the elements of the array in such a way that the even values appear before odd values.
- The method has two index variables i and j where i starts from the first element of the array which means it is positioned at the left of the array and j is positioned at the last element of the array which is 1 minus the length of the array. This means j is placed at the right of the array.
- The first while loop keeps executing till i is less than j.
- The second while loop keeps checking if the element at i-th index is even. This is checked by taking mod of the element at i index with 2. If the result of the mod is equal to 0 this means that the element is completely divisible by 2 so its an even number. Then the value of i is incremented by 1.
- The third while loop contains j index which moves through the array from right and checks for the odd elements. This is checked by taking mod of the element at j index with 2. If the result of the mod is equal to 1 this means that the element is not completely divisible by 2 so its an odd number. Then the value of j is decremented by 1.
- So loops keeps incrementing i index until an odd number is seen and keeps decrementing j index until even number is seen.
- If i is less than j then array element at i-th index is swapped by array element at j-th index.
- Finally the main() function calls this method evenBeforeOdd () and passes an array containing 5, 4, 2, 11, 9, 10, 4, 7, 3 to display even values before odd values in the output.
- The code along with the output is attached.

