Chapter 18 Recursion

Ace your homework & exams now with Quizwiz!

recursive

A ____________ method is the one that calls itself.

tail

A _______ recursive method is efficient for reducing stack size.

The method runs infinitely and causes a StackOverflowError.

Analyze the following recursive method. public static long factorial(int n) { return n * factorial(n - 1); }

recursiveBinarySearch(list, key, low, high)

Fill in the code to complete the following method for binary search. public static int recursiveBinarySearch(int[] list, int key) { int low = 0; int high = list.length - 1; return __________________________; } public static int recursiveBinarySearch(int[] list, int key, int low, int high) { if (low > high) // The list has been exhausted without a match return -low - 1; // Return -insertion point - 1 int mid = (low + high) / 2; if (key < list[mid]) return recursiveBinarySearch(list, key, low, mid - 1); else if (key == list[mid]) return mid; else return recursiveBinarySearch(list, key, mid + 1, high); }

The base cases are (1) s.length() <= 1 and (2) s.charAt(0) != s.charAt(s.length - 1) When invokingisPalindrome("abdxcxdba"), the isPalindrome method is called 5 times.

For the isPalindrome method in Listing 18.3, what are the base cases? How many times is this method called when invoking isPalindrome("abdxcxdba")?

0

Show the output of the following code public class Test1 { public static void main(String[] args) { System.out.println(f2(2, 0)); } public static int f2(int n, int result) { if (n == 0) return 0; else return f2(n - 1, n + result); } }

(a) Sum is 15 (5 + 4 + 3 + 2 + 1 = 15) (b) 7654321

Show the output of the following programs and identify base cases and recursive calls. (a) public class Test { public static void main(String[] args) { System.out.println( "Sum is " + xMethod(5)); } public static int xMethod(int n) { if (n == 1) return 1; else return n + xMethod(n - 1); } } (b) public class Test { public static void main(String[] args) { xMethod(1234567); } public static void xMethod(int n) { if (n > 0) { System.out.print(n % 10); xMethod(n / 10); } } }

infinite

An ____________ recursion is the one that never stops.

n is 1

In the following method, what is the base case? static int xMethod(int n) { if (n == 1) return 1; else return n + xMethod(n - 1); }

True

Recursion is a technique that leads to elegant solutions to problems that are difficult to program using simple loops.

When a method is invoked, its contents are placed into a stack. If a method is recursively invoked, it is possible that the stack space is exhausted. This causes stack overflow.

What is a cause for a stack-overflow exception?

10 Explanation: 4 + 3 + 2 + 1 = 10

What is the return value for xMethod(4) after calling the following method? static int xMethod(int n) { if (n == 1) return 1; else return n + xMethod(n - 1); }

f2 is tail recursion, but f1 is not

Analyze the following functions; public class Test1 { public static void main(String[] args) { System.out.println(f1(3)); System.out.println(f2(3, 0)); } public static int f1(int n) { if (n == 0) return 0; else { return n + f1(n - 1); } } public static int f2(int n, int result) { if (n == 0) return result; else return f2(n - 1, n + result); } }

One or more base cases (the simplest case) are used to stop recursion. Every recursive call reduces the original problem, bringing it increasingly close to a base case until it becomes that case.

Describe the characteristics of recursive methods.

6

How many times is the factorial method in Listing 18.1 invoked for factorial(5)?

7

How many times is the recursive moveDisks method invoked for 3 disks?

15

How many times is the recursive moveDisks method invoked for 4 disks?

n <= 0

What are the base cases in the following recursive method? public static void xMethod(int n) { if (n > 0) { System.out.print(n % 10); xMethod(n / 10); } }

f(n) = 2 if n = 1 f(n) = 2 * 2^(n-1) for (n > 1)

Write a recursive mathematical definition for computing 2 n for a positive integer n.

f(n) = x if n = 1 f(n) = x * x^(n-1) for (n > 1)

Write a recursive mathematical definition for computing x n for a positive integer n and a real number x.

Recursion

____________ is an alternative form of program control. It is essentially repetition without a loop.

15

How many times is the fib method in Listing 18.2 invoked for fib(5)?

25 times (Why?): number of time fib is invoked in fib(0) = 1 number of time fib is invoked in fib(1) = 1 number of time fib is invoked in fib(2) = 1+ number of time fib is invoked in fib(1)+number of time fib is invoked in fib(2) =1+1+1=3 number of time fib is invoked in fib(3) = 1+ number of time fib is invoked in fib(1)+number of time fib is invoked in fib(2) = 1+1+3=5 number of time fib is invoked in fib(4) = 1+ number of time fib is invoked in fib(2)+number of time fib is invoked in fib(3) = 1+3+5=9 number of time fib is invoked in fib(5) = 1+ number of time fib is invoked in fib(3)+number of time fib is invoked in fib(4) = 1+5+9=15 number of time fib is invoked in fib(6) = 1+ number of time fib is invoked in fib(4)+number of time fib is invoked in fib(5) = 1+9+15=25

How many times is the fib method in Listing 18.2 invoked for fib(6)?

The isPalindrome method in Listing 18.4, sort method in Listing 18.5, and binarySearch method in Listing 18.6 are tail-recursive.

Identify tail-recursive methods in this chapter.

A. displayTriangles(order - 1, p1, p12, p31); B. displayTriangles(order - 1, p12, p2, p23); C. displayTriangles(order - 1, p31, p23, p3);

In LiveExample 18.9, to draw three smaller triangles recursively, the program invokes:

(a) n is double. There is no guarantee that n != 0 will be eventually false. (b) Infinite recursion due to new Test() inside the constructor Test().

What is wrong in the following method? (a) public class Test { public static void main(String[] args) { xMethod(1234567); } public static void xMethod(double n) { if (n != 0) { System.out.print(n); xMethod(n / 10); } } } (b) public class Test { public static void main(String[] args) { Test test = new Test(); System.out.println(test.toString()); } public Test() { Test test = new Test(); } }

A. Every recursive method must have a base case or a stopping condition. B. Every recursive call reduces the original problem, bringing it increasingly closer to a base case until it becomes that case. C. Infinite recursion can occur if recursion does not reduce the problem in a manner that allows it to eventually converge into the base case.

Which of the following statements are true? A. Every recursive method must have a base case or a stopping condition. B. Every recursive call reduces the original problem, bringing it increasingly closer to a base case until it becomes that case. C. Infinite recursion can occur if recursion does not reduce the problem in a manner that allows it to eventually converge into the base case. D. Every recursive method must have a return value. E. A recursive method is invoked differently from a non-recursive method.

The program displays 5 4 3 2 1 and then raises an ArrayIndexOutOfBoundsException. Explanation: xMethod(x, 5) is invoked, then xMethod(x, 4), xMethod(x, 3), xMethod(x, 2), xMethod(x, 1), xMethod(x, 0). When invoking xMethod(x, 0), a runtime exception is raised because System.out.print(' '+x[0-1]) causes array out of bound.

Analyze the following code: public class Test { public static void main(String[] args) { int[] x = {1, 2, 3, 4, 5}; xMethod(x, 5); } public static void xMethod(int[] x, int length) { System.out.print(" " + x[length - 1]); xMethod(x, length - 1); } }

The midpoint between p1 and p2 is ((p1.x + p2.x)/2, (p1.y + p2.y)/2), which can be obtained by invoking p1.midpoint(p2).

How do you obtain the midpoint between two points?

Program A produces the output 4 3 2 1 and Program B prints 4 3 2 1 1 1 .... 1 infinitely. Explanation: In Program B, xmethod(5) invokes xmethod(4), xmethod(4) invokes xmethod(3), xmethod(3) invokes xmethod(2), xmethod(2) invokes xmethod(1), xmethod(1) returns control to xmethod(2), xmethod(2) invokes xmethod(1) because of the while loop. This continues infinitely.

Analyze the following two programs: A: public class Test { public static void main(String[] args) { xMethod(5); } public static void xMethod(int length) { if (length > 1) { System.out.print((length - 1) + " "); xMethod(length - 1); } } } B: public class Test { public static void main(String[] args) { xMethod(5); } public static void xMethod(int length) { while (length > 1) { System.out.print((length - 1) + " "); xMethod(length - 1); } } }

(s.charAt(0) != s.charAt(s.length() - 1)) // Base case

Fill in the code to complete the following method for checking whether a string is a palindrome. public static boolean isPalindrome(String s) { if (s.length() <= 1) // Base case return true; else if _____________________________ return false; else return isPalindrome(s.substring(1, s.length() - 1)); }

isPalindrome(s, low + 1, high - 1)

Fill in the code to complete the following method for checking whether a string is a palindrome. public static boolean isPalindrome(String s) { return isPalindrome(s, 0, s.length() - 1); } public static boolean isPalindrome(String s, int low, int high) { if (high <= low) // Base case return true; else if (s.charAt(low) != s.charAt(high)) // Base case return false; else return _______________________________; }

fib(index - 1) + fib(index - 2) fib(index - 2) + fib(index - 1)

Fill in the code to complete the following method for computing a Fibonacci number. public static long fib(long index) { if (index == 0) // Base case return 0; else if (index == 1) // Base case return 1; else // Reduction and recursive calls return __________________; }

n * factorial(n - 1) factorial(n - 1) * n

Fill in the code to complete the following method for computing factorial. /** Return the factorial for a specified index */ public static long factorial(int n) { if (n == 0) // Base case return 1; else return _____________; // Recursive call

sort(list, list.length - 1)

Fill in the code to complete the following method for sorting a list. public static void sort(double[] list) { ___________________________; } public static void sort(double[] list, int high) { if (high > 1) { // Find the largest number and its index int indexOfMax = 0; double max = list[0]; for (int i = 1; i <= high; i++) { if (list[i] > max) { max = list[i]; indexOfMax = i; } } // Swap the largest with the last number in the list list[indexOfMax] = list[high]; list[high] = max; // Sort the remaining list sort(list, high - 1); } }

/** Return the Fibonacci number for the specified index */ public static long fib(long index) { return fib(index, 1, 0); } /** Auxiliary tail-recursive method for fib */ private static int fib(long index, int next, int result) { if (index == 0) return result; else return fib(index - 1, next + result, next); }

Rewrite the fib method in Listing 18.2 using tail recursion.

(a) The output is 5 4 3 2 1 (b) The output is 1 2 3 4 5

Show the output of the following two programs: (a) public class Test { public static void main(String[] args) { xMethod(5); } public static void xMethod(int n) { if (n > 0) { System.out.print(n + " "); xMethod(n - 1); } } } (b) public class Test { public static void main(String[] args) { xMethod(5); } public static void xMethod(int n) { if (n > 0) { xMethod(n - 1); System.out.print(n + " "); } } }

B. Recursive methods usually take more memory space than non-recursive methods. C. A recursive method can always be replaced by a non-recursive method. D. In some cases, however, using recursion enables you to give a natural, straightforward, simple solution to a program that would otherwise be difficult to solve.

Which of the following statements are true? A. Recursive methods run faster than non-recursive methods. B. Recursive methods usually take more memory space than non-recursive methods. C. A recursive method can always be replaced by a non-recursive method. D. In some cases, however, using recursion enables you to give a natural, straightforward, simple solution to a program that would otherwise be difficult to solve.

The Fibonacci series begins with 0 and 1, and each subsequent number is the sum of the preceding two numbers in the series.

Which of the following statements are true? A. The Fibonacci series begins with 0 and 1, and each subsequent number is the sum of the preceding two numbers in the series. B. The Fibonacci series begins with 1 and 1, and each subsequent number is the sum of the preceding two numbers in the series. C. The Fibonacci series begins with 1 and 2, and each subsequent number is the sum of the preceding two numbers in the series. D. The Fibonacci series begins with 2 and 3, and each subsequent number is the sum of the preceding two numbers in the series.

A , B , D

Which of the following statements are true? a. Any recursive method can be converted into a nonrecursive method. b. Recursive methods take more time and memory to execute than nonrecursive methods. c. Recursive methods are always simpler than nonrecursive methods. d. There is always a selection statement in a recursive method to check whether a base case is reached.

f(n) = 1 if n = 1 f(n) = f(n-1) + n for (n > 1)

Write a recursive mathematical definition for computing 1 + 2 + 3 + ... + n for a positive integer n.


Related study sets

Statistics : Chapter 1.5 BIAS IN SAMPLING

View Set

BUS2 - 130 Intro to Marketing (Chapter 4)

View Set

Kyle and Carman PrepU Chapter 26: Nursing Care of the Child With an Alteration in Metabolism/Endocrine Disorder

View Set

Business Law Ch.29: Personal Property & Bailments

View Set

Linear Algebra Assignments True/False

View Set

Česky krok za krokem 1, lekce 11: Cestování

View Set

practices lesson 10 FHA insured loans

View Set

EXAM - Section 11, Unit 1: Employment and Cooperation Agreements in Arizona

View Set