logo Practice-It logo

evenBeforeOdd

Language/Type: Java arrays mod
Author: Marty Stepp (on 2010/12/28)

Write a method named evenBeforeOdd that accepts an array of integers as a parameter and rearranges its elements so that all even values appear before all odds. For example, if the following array is passed to your method:

int[] numbers = {5, 2, 4, 9, 3, 6, 2, 1, 11, 1, 10, 4, 7, 3};

Then after the method has been called, one acceptable ordering of the elements would be:

                {4, 2, 4, 10, 2, 6, 3, 1, 11, 1, 9, 5, 7, 3}

The exact order of the elements does not matter, so long as all even values appear before all odd values. For example, the following would also be an acceptable ordering:

                {2, 2, 4, 4, 6, 10, 1, 1, 3, 3, 5, 7, 9, 11}

Do not make any assumptions about the length of the array or the range of values it might contain. For example, the array might contain no even elements or no odd elements. You may assume that the array is not null.

You should not use any temporary arrays to help you solve this problem. (But you may declare as many simple variables as you like, such as ints.) You also may not use any other data structures such as Strings, or others that were not taught in CSE 142 such as the ArrayList class from Chapter 10. You also should not use Arrays.sort in your solution.

Hint: Look for elements that are at inappropriate places in the array and move them to better locations.

Type your solution here:


This is a method problem. Write a Java method as described. Do not write a complete program or class; just the method(s) above.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.