Java Reference
In-Depth Information
16. The following version of the code has improved efficiency:
public static int fibonacci(int n) {
if (n <= 2) {
return 1;
} else {
return fibonacci(n, 3, 1, 1);
}
}
private static int fibonacci(int n, int i, int prev, int curr) {
if (n == i) {
return prev + curr;
} else {
return fibonacci(n, i + 1, curr, prev + curr);
}
}
17. A fractal is an image that is recursively constructed to contain smaller versions of
itself. Recursive methods are useful when drawing fractal images because they can
elegantly express the recursive nature of the images.
18. public static void drawHexagon(Graphics g, Point position, int
size) {
Polygon poly = new Polygon();
poly.addPoint(position.x, position.y + size / 2);
poly.addPoint(position.x + size / 3, position.y);
poly.addPoint(position.x + 2 * size / 3, position.y);
poly.addPoint(position.x + size, position.y + size / 2);
poly.addPoint(position.x + 2 * size / 3, position.y +
size);
poly.addPoint(position.x + size / 3, position.y + size);
g.drawPolygon(poly);
}
Chapter 13
1. You can perform a sequential search over the array using a for loop, or you can
sort the array using Arrays.sort and then perform a binary search over it using
Arrays.binarySearch .
2. A sequential search should be used on an array of Point objects because they do
not implement Comparable .
3. Arrays.binarySearch and Collections.binarySearch can be used success-
fully if the array or collection contains elements that are sorted, according to either
their natural ordering or the ordering of a Comparator .
 
Search WWH ::




Custom Search