Sample Exam 1
1.
Implement a Java class that represents a piggy bank that can hold quarters, dimes, nickels and pennies. Its methods should include:
a constructor that creates an empty piggy bank (with 0 coins of any kind)
a constructor that creates a piggy bank preloaded with coins (the amount of money is specified as an argument; your constructor should calculate from this how many coins of each type are present, assuming that the amount is represented by the smallest possible number of coins)
accessor methods that report the number of each type of coin present
an accessor method that reports the total amount of money present (in cents)
a deposit method that adds the amount of money specified by its argument; like the second constructor specified above, the method should adjust the coin totals with the assumption that the monetary amount uses the fewest possible coins
2.
We know that serial search is O(N) and binary search is O(log N) for sorted data.
Suppose you don’t know whether or not your data set is sorted. Rank the following search/sort combinations in order from the most efficient to the least efficient (considering computation time only). For ranking, 1 is the fastest, 5 the slowest. Show the Big O values you used to determine your ranking:
Initial data condition unsorted
Sorting algorithm applied selectionsort
Searching algorithm applied serial search
Rank / Big O unsorted sorted quicksort insertionsort binary search serial search sorted unsorted quicksort mergesort binary search serial search
3.
Consider the array pictured below in its initial state:
65 11 27 8 32 91
8
14 84
Suppose one of the quadratic algorithms discussed in class was applied to this array; after three iterations of this algorithm, the partially sorted array looks like this:
11 27 65 32 91 14 84
A.
Which algorithm was used?
B.
Show the array after the next iteration of the same algorithm:
C.
Show the array after four iterations of the other algorithm:
4.
Show the output from the following Java method, if the initial number supplied to the doIt method is 5:
Output: public void doIt ( int n) { if (n <= 0)
System.out.println( "!" ); else {
System.out.print( "^" );
doIt(n-1);
System.out.print( "-" );
}
}
5.
Implement the doIt method using iteration (loop(s)) instead of recursion. Write pre- and postcondition statements for your implementation.
6.
Perform a Big-O analysis on the code you wrote in question 5.