Reference semantics questions

posted by: Ms. Martin 31 January 2010 No Comment

I would like you to comment these using the precondition/postcondition commenting style we have recently seen.  What must be true in order for the method to run as promised?  What will be true after the method has run?

Remember that method that modify arrays don’t need to return them, necessarily…

Double method

Write a static method doubleAll that takes an array of integers as a parameter and doubles each of its elements.

Reverse method

Write a static method reverse that takes an array as a parameter and reverses its content.  Yes, we will have done this on the board, but it’s excellent practice to try your hand at again and get to run.

Swap method

Write a static method swap that takes an array of integers and two indexes as parameters.  Your method should swap the elements at those two indexes.

evenBeforeOdd

Write a static 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.
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 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.)  Hint: Look for elements that are at inappropriate places in the array and move them to better locations.
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>