15-100 Sections U-V-AA / Spring 2009 / Quiz 9
3 Questions – 30 minutes
1. Short Answers (Sorting and Recursion)
a.
Sort the following array using insertionsort. Show the entire array
after each swap.
The first step is done for you.
5 3
2 4 (initial array)
3 5 2 4 (after first swap)
b.
Sort the following array using selectionsort. Show the entire array
after each swap.
5 3
2 4 (initial array)
c. In two words, what usually happens when a recursive method does not include a base case?
d.
Write a short
recursive method, factorial, that takes a non-negative number n and returns
n! (n factorial, which is the product of the numbers from 1 to n) using
recursion. Your method may not use any kind of iterative loop – no “for”,
“while”, or “do-while” loops allowed!. Note that 0! equals 1. Also, if n is
negative, return -1.
2.
Two-Dimensional Arrays
Write a method, matrixSum, that takes two possibly-null 2d arrays of int’s
(which may not be modified) and returns a third 2d array of int’s where each
element in the returned array is the sum of the corresponding elements in the
two argument arrays. For example, given these two arrays:
{ {
2, 4, 6 },
{ 3, 1, 5 } }
and:
{ {
7, 2, 1 },
{
5, 3, 0 } }
your method would return:
{ {
9, 6, 7 },
{ 8, 4, 5 } }
Also, return null if either argument array is null or if the two argument arrays
are not the same dimensions.
3. Event-Based
Programming
Write a program (by extending
JComponentWithEvents) that works exactly as such:
a. Initially, a small oval bounces up and down in the middle of the window.
b. If the user hits ‘p’, the movement pauses until the user hits ‘p’ again to unpause.
c. If the user hits ‘s’, the oval changes to a square and keeps bouncing (or, if already a square, the ‘s’ is simply ignored).
Carpe diem!