Combined Qs Comps
Using the evaluatePostfix algorithm, evaluate the following postfix expression. a b + c d -* Assume that a =5,b =7, c = 6, and d = 2. a.48 b.39 c.55 d.none of the above
48
The Java Class Library interface Queue method to put an entry on the back of a queue that throws an exception of the method fails is a. add b. offer c. put d. poll
A
The ____ ADT organizes its entries according to the order in which they were added. a. queue b. stack c. list d. priority queue
A
The _____ ADT that has operations to add, remove, or retrieve entries at both the front and back of a queue is called a a. deque b. reversible queue c. reversible stack d. all of the above
A
The method for adding a new item to the back of a queue is called a. enqueue b. dequeue c. getFront d. none of the above
A
The method for removing an item from the front of a queue is called a. dequeue b. enqueue c. getFront d. none of the above
A
The method for retrieving the queue's front entry without altering the queue is called a. getFront b. enqueue c. dequeue d. none of the above
A
To efficiently remove a node at the end of a linked chain implementation of a queue requires a a. tail reference b. traversal c. extra reference in the node pointing to the previous node d. none of the above
A
What is the entry returned by the peek method after the following stack operations: push(A), push(R), pop(), push(D), pop(), push(L), pop(), push(J), push(S), pop(), pop().
A
What is the entry returned by the peekmethod after the following stack operations.push(A), push(R), pop(), push(D), pop(), push(L), pop(), push(J), push(S), pop(), pop() a.A b.S c.L d.D
A
Unlike a stack, a queue does not restrict access to its entries.
False
(Binary) search trees
For each node in a binary search tree The node's data is greater than all the data in the node's left subtree The node's data is less than all the data in the node's right subtree
Can you search the following array using binary search? int[] A = {6, 5, 4, 2, 0, 1, -1, -17};
No. Binary search can be applied to a sorted array only
In an array-based implementation of a queue, keeping the front entry of the queue at queue[0] is inefficient.
True
Queues are used in operating systems.
True
Heaps Implementation: array
When a binary tree is complete, using an array instead of linked nodes is desirable. • Has a parent at index i/2, unless the node is the root (i is 1) • Has any children at indices 2i and 2i + 1 Note: To add a new entry to a heap, you begin at the next available position for a leaf. You follow a path from this leaf toward the root until you find the correct position for the new entry. As you do, you move entries from parent to child to ultimately make room for the new entry.
When adding a node to a two-part circular linked chain implementation of a queue we insert the new node into the chain
after the node that freeNode reference
Consider the following recursive code snippet: public int mystery(int n, int m) { if (n == 0) { return 0; } if (n == 1) { return m; } return m + mystery(n - 1, m); } What parameter values for n would cause an infinite recursion problem in the following method?
all n with n < 0
A reasonable action when attempting to remove an item from an empty stack is a.assume a precondition that the stack is not empty has been met b.throw an exception c.return null d.all of the above
all of the above
A two-part circular linked chain implementation of a queue
all of the above
In a two-part circular linked chain implementation of a queue
all of the above
In an array-based implementation of a queue, a possible solution to dealing with the full condition is to
all of the above
The activation record contains a.the method's arguments b.local variables c.a copy of the program counter d.all of the above
all of the above
When adding a node to a two-part circular linked chain implementation of a queue
all of the above
When removing a node from a two-part circular linked chain implementation of a queue
all of the above
_____ is an alias for the name of the pop method. a.pull b.remove c.delete d.all of the above
all of the above
_____ happens when a bag becomes full in a linked list implementation.
an OutofMemoryError will occur
Consider the following recursive code snippet: public int mystery(int n, int m) { if (n == 0) { return 0; } if (n == 1) { return m; } return m + mystery(n - 1, m); } What value is returned from a call to mystery(3,6)? a. 6 b. 18 c. 729 d. 3
b. 18
Given the following code snippet: public static int newCalc(int n) { if (n < 0) { return -1; } else if (n < 10) { return n; } else { return (1 + newCalc(n / 10)); } } What value will be returned when this code is executed with a call to newCalc(15)? a. 5 b. 2 c. 5.5 d. 2.5
b. 2
A unique permutation is one that is different from any other generated permutation. How many unique permutations does the string "bee" have? a. 4 b. 3 c. 2 d. 5
b. 3
Complete the recursive method below, which is designed to return the number of matchsticks needed to form n squares. public static int matchsticks(int squares) { if (squares == 1) // 1 square can be formed with 4 matchsticks { return 4; } else { return ___________________________ } } a. matchsticks(squares + 4); b. 3 + matchsticks(squares - 1); c. 4 + matchsticks(squares - 1); d. 4 * squares;
b. 3 + matchsticks(squares - 1);
What question should you keep in mind when debugging a recursive method? a) Does each base case produce a result that is correct for that case? b) Are there enough base cases? c) Is at least one of the cases a base case that has no recursive call? d) All of the above.
d) All of the above.
Consider the recursive version of the fib method from the textbook shown below: public static long fib(int n) { if (n <= 2) { return 1; } else { return fib(n - 1) + fib(n - 2); } } How many more recursive calls to fib will be made from the original call of fib(7) than from the original call of fib(6) (not counting the original calls)? a. 1 b. 5 c. 2 d. 10
d. 10
Consider the recursive method shown below: public static int strangeCalc(int bottom, int top) { if (bottom > top) { return -1; } else if (bottom == top) { return 1; } else { return bottom * strangeCalc(bottom + 1, top); } } What value will be returned with a call to strangeCalc(4,7)? a. -1 b. 1 c. 840 d. 120
d. 120
Consider the recursive square method shown below that takes a non-negative int argument. public int square(int n) { return square(n, n); } public int square(int c, int n) { if (c == 1) { return n; } else { return n + square(c - 1, n); } } Assume that the last return statement is changed to this: return n * square(c - 1, n); What would a call to square(4) return? a. 16 b. 64 c. 4 d. 256
d. 256
Consider the following recursive code snippet: public int mystery(int n, int m) { if (n == 0) { return 0; } if (n == 1) { return m; } return m + mystery(n - 1, m); } What value is returned from a call tomystery(1,5)? a. 6 b. 1 c. 11 d. 5
d. 5
Consider the method powerOfTwo shown below: public boolean powerOfTwo(int n) { if (n == 1) // line #1 { return true; } else if (n % 2 == 1) // line #2 { return false; } else { return powerOfTwo(n / 2); // line #3 } } How many recursive calls are made from the original call of powerOfTwo(64) (not including the original call)? a. 4 b. 8 c. 2 d. 6
d. 6
Recursion does NOT take place if any of the following happen: I method A calls method B, which calls method C, which calls method B II method A calls method B, which calls method A III method A calls method B, B returns, and A calls B again a. I b. II c. I and II d. III
d. III
Consider the fib method from the textbook shown below: public static long fib(int n) { if (n <= 2) { return 1; // line #1 } else { return fib(n - 1) + fib(n - 2); // line #2 } } Assume line #1 is changed to this: if (n <= 2) { return 2; } How will this change affect the result of calling fib(7)? a. It will add 8 to the return from fib(7) b. It will add 2 to the return from fib(7) c. It will add 4 to the return from fib(7) d. It will double the return from fib(7)
d. It will double the return from fib(7)
Consider the method powerOfTwo shown below: public boolean powerOfTwo(int n) { if (n == 1) // line #1 { return true; } else if (n % 2 == 1) // line #2 { return false; } else { return powerOfTwo(n / 2); // line #3 } } What is the best interpretation of line #1? a. 1 is an invalid choice for n b. One is not a power of two c. Any multiple of one is a power of two d. One is a power of two
d. One is a power of two
When a recursive method is called, and it does not perform recursion, what must be true? a. All recursive case conditions were true. b. An exception will occur in the method. c. One recursive case condition was true. d. The terminating condition was true.
d. The terminating condition was true.
Ordinary algebraic expressions are also known as a.infix expressions b.postfix expressions c.prefix expressions d.all of the above
infix expressions
Placing the Node class inside the LinkedBag class makes it an _____.
inner class
_____ is an alias for the push method. a.insert b.pull c.delete d.all of the above
insertt
In a circular array-based implementation of a queue implementation where one unused location is used to differentiate between the front and back of the queue, the frontIndexis _____ than the backIndex.
one more
In a circular array-based implementation of a queue, the initial size of the array should be
one more than the queue's initial capacity
Graph ADT implementations: adjacency matrix
private List<List<Boolean>> adjacencyMatrix - uses 1s and 0s for unweighted graphs An adjacency matrix uses a fixed amount of space that depends on the number of vertices, but not the number of edges, in a graph. The adjacency matrix for a sparse graph waste space, because the graph has relatively few edges. Seeing whether an edge exists between any two given vertices of a graph can be done quickly when you use an adjacency matrix. But you need to scan an entire row of the matrix if you want to know all the neighbors of a particular matrix. Let M be the adjacency matrix: M•M•...•M = M^k. k = the number of times the matrix is multiplied by iself This matrix M^k gives us in the ith row, ith column = #k-edge path from its vertex to the jth vertex.
Assume we are using quicksort to sort an array in ascending order. What can we conclude about the indexes of two pivot elements placed in consecutive recursive calls?
they are randomly located
The Stack ADT may be implemented with _____.
- an array - a vector - a linked-chain
char
16 bits
In a circular array-based implementation of a queue, what is the performance when the enqueue operation does not resize the array? a. O(1) b. O(log n) c. O(n) d. O(n2)
A
Java sorting implementations sort objects that implement the _____ interface.
Comparable
The ArrayDeque class implements the Stack interface.
False
What is the purpose of a recursive helper method? a. Shield the user of the recursive method from the recursive details. b. Speed up the execution. c. Add another base case. d. Eliminate the recursion.
NOT c. Add another base case.
When a circular linked chain has one node, the node references itself.
True
69) What is the purpose of a recursive helper method? a) Shield the user of the recursive method from the recursive details. b) Speed up the execution. c) Eliminate the recursion. d) Add another base case.
a
For the infix expression (a + b) * (c - d) / (e + f), the corresponding postfix expression would be _____.
a b + c d ‑ * e f + /
91) In recursion, the recursive call is analogous to a loop ____. a) call b) iteration c) termination d) return
b
95) Which of the following strings is a palindrome? a) "Test" b) "B" c) "canal" d) "salami"
b
80) Consider the fib method from the textbook shown below: public static long fib(int n) { if (n <= 2) { return 1; // line #1 } else { return fib(n - 1) + fib(n - 2); // line #2 } } Assume line #2 is changed to this: else { return 2 * fib(n - 1) + 2 * fib(n - 2); } What effect will this change have? a) This will return 5 from fib(4) b) This will return 8 from fib(4) c) This will return 10 from fib(4) d) This will cause an exception on a call fib(4)
c
In recursion, the recursive call is analogous to a loop ____. a. call b. termination c. iteration d. return
c. iteration
Complete the code for the myFactorial recursive method shown below, which is intended to compute the factorial of the value passed to the method: public int myFactorial(int anInteger) { if (anInteger == 1) { return 1; } else { ______________________ } } a. return ((anInteger - 1) * (myFactorial(anInteger))); b. return (anInteger * (myFactorial(anInteger))); c. return (anInteger * (myFactorial(anInteger - 1))); d. return ((anInteger - 1)*(myFactorial(anInteger - 1)));
c. return (anInteger * (myFactorial(anInteger - 1)));
Remove all entries from the stack
clear
105) Recursion will take place if any of the following happen: I method A calls method B, which calls method C II method A calls method B, which calls method A III method A calls method A a) I b) I and II c) II d) II and III
d
60) Complete the following code snippet, which is intended to be a recursive method that will find the sum of all elements in an array of double values from index to the end of the array: // return the sum of all elements in arr[] public static double findSum(double arr[], int index) { if (index == 0) { return arr[index]; } else { _____________________ } } Assume that this method would be called using an existing array named myArray as follows: findSum(myArray, myArray.length - 1); a) return (findSum(arr, index + 1)); b) return (findSum(arr, index - 1)); c) return (arr[index] + findSum(arr, index + 1)); d) return (arr[index] + findSum(arr, index - 1));
d
In the Ch 6 linked-chain implementation of a Stack ADT, when a node is popped from the stack: a) the original first node will no longer be referenced b) the original first node will be deallocated c) the new first node will reference what was the second node in the chain d) all of the above
d) all of the above
A recursive method without a special terminating case would _________ a. not be recursive. b. be more efficient. c. end immediately. d. never terminate.
d. never terminate
The practice of checking for anticipated errors in your program is known as _____ programming.
fail-safe
In a circular array-based implementation of a queue, frontIndexis equal to one less than backIndexwhen the queue is full.
false
In a circular array-based implementation of a queue, frontIndexis equal to one more than backIndexwhen the queue is empty.
false
In a linked chain implementation of a queue, the enqueue operation could potentially be dependent on the other entries and will require a search.
false
In a linked chain implementation of a queue, the enqueue operation requires a traversal to the end of the chain to insert a new entry onto the queue.
false
In an array-based implementation of a queue, inserting and deleting entries is accomplished using modulo arithmetic.
false
In an array-based implementation of a queue, keeping the front entry of the queue at queue[0] is inefficient.
false
The bottom item in a stack was the last item added.
false
The first item added to a stack is the first one removed.
false
When a circular linked chain is used to represent a queue, it is not necessary to maintain a firstNodedata field.
false
You can only pop from the top of the stack but you can peek at any entry on the stack.
false
infix expressions are easier to evaluate than postfix expressions.
false
A binary search is generally ____ a linear search.
faster than
An object in Java is a software artifact that contains state which are its _____ and behaviors which are its _____.
fields; methods
The merge sort algorithm presented in section 14.4, which sorts an array of integers in ascending order, uses the merge method which is partially shown below. Select the condition that would be needed to complete the method so that the elements are sorted in descending order. private static void merge(int[] first, int[] second, int[] a) int iFirst = 0; int iSecond = 0; int j = 0; while (iFirst < first.length && iSecond < second.length) if (_____________________________) a[j] = first[iFirst]; iFirst++; else a[j] = second[iSecond]; iSecond++; j++; // rest of the method follows here
first [iFirst] > second [ iSecond]
_____ is an alias for the peek method. a.getTop b.pull c.look d.all of the above
getTop
Measuring the growth of an algorithm's time requirement grows as the problem size increases is called the _____.
growth rate function
Which method does the interface Iterator specify?
hasNext next remove
Which of the sorts in the textbook can be characterized by the fact that the best case will have a running time of θ(n) if the data is already sorted? I quicksort II selection sort III insertion sort
insertion sort
Which sort algorithm starts with an initial sequence of size 1, which is assumed to be sorted, and increases the size of the sorted sequence in the array in each iteration?
insertion sort
______14) Consider the following code snippet: public static void sort(int[] a) for (int i = 1; i < a.length; i++) int next = a[i]; int j = i; while (j > 0 && a[j - 1] > next) a[j] = a[j - 1]; j--; a[j] = next; What sort algorithm is used in this code?
insertion sort
The code segment below displays a pattern of asterisks. Select an expression to complete the code segment so that the resulting algorithm has O(n) running time. for (int k = 0; k < n; k++) for _______________________ System.out.print("*"); System.out.println();
int j = 1; j < = 10; j++
A Java _____ is a program component that declares several public method signatures and defines public named constants. These components are used when the _____ keyword is invoked.
interface; implements
The precedence of an operator in a postfix expression a.is implied by the order in which the operators and operands occur b.is always left to right c.is always right to left d.depends on the compiler implementation
is implied by the order in which the operators and operands occur
The precedence of an operator in a postfix expression _____.
is implied by the order in which the operators and operands occur
In a vector implementation of a Stack ADT, you check for an empty stack using which vector method?
isEmpty
In big-Oh notation, suppose an algorithm requires an order of n the number of elements affect the number of visits?
it number of visits goes up by a factor of eight
In recursion, the recursive call is analogous to a loop ____.
iteration
Assume we are using quicksort to sort an array in ascending order. Into which array location does quicksort's strategy place a pivot element after partitioning?
its final correct location
Remove an entry from the stack
pop
Problem size is defined as _____.
the number of items an algorithm processes
If iteration has ended, the next method
throws a NoSuchElementException
A stack restricts access to its entries.
true
All entries in the stack ADT must have the same data type.
true
Each node in an ordinary linked chain references only the next node.
true
In a circular array-based implementation of a queue, the available locations are not contiguous.
true
In a circular array-based implementation of a queue, you cannot use only frontIndexto determine when a queue is full.
true
In a linked chain implementation of a queue, when both the firstNode and lastNode entries are null, the chain is empty.
true
In the program stack, the second record on the stack belongs to the method that called the current method.
true
Parentheses override the rule of operator precedence
true
Pull is an alias for the pop method.
true
When a circular linked chain has one node, the node references itself.
true
You cannot reach the bottom item in a stack without popping all of the other items off first.
true
You need two external references for a circular doubly linked chain, one for the firstNode and one forthe lastNode.
true
When you write a program for an algorithm and it is taking much longer than expected you should _____.
try to design a better algorithm
A _____ is a named location in memory whose contents can change over time.
variable
boolean
vm dependent
For the infix expression w + x * y / z, the corresponding postfix expression would be _____.
w x y * z / +
When would you choose a two-part circular chain over a circular chain?
when you frequently add an entry after removing one
Given the following infix expression, which one of the following is the corresponding postfix expression? w + x * y / z a.w x y * z / + b.w x + y z * / c.w x y q + * / d.none of the above
wxy*z/+
double
64 bits
2-3 Tree: self-balancing
A 2-3 tree is a general search tree whose interior nodes must have either two or three children and whose leaves occur on the same level. A 2-3 tree is completely balanced. 2-node contains one data item s and has two children 3-node contains two data items, s and l and has three children The logic: If you divide things into groups of 2 and 3, it always works when you have at least 2 things
Consider the getArea method shown below. public int getArea() { if (width <= 0) { return 0; } // line #1 else if (width == 1) { return 1; } // line #2 else { Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } } Assume lines #1 and #2 were replaced with this: if (width == 1) { return 1; } // replacement for lines #1 and #2 What will happen when this code is executed?
A negative or zero width would cause problems.
In a circular array-based implementation of a queue, frontIndex is equal to one less than backIndex when the queue is full.
False
In a circular array-based implementation of a queue, frontIndex is equal to one more than backIndex when the queue is empty.
False
In a linked chain implementation of a queue, the enqueue operation could potentially be dependent on the other entries and will require a search.
False
In a linked chain implementation of a queue, the enqueue operation requires a traversal to the end of the chain to insert a new entry onto the queue.
False
Merge sort is a(n) ____ algorithm.
O (n log (n)
Binary search is an ____ algorithm.
O(log n)
In a circular array-based implementation of a queue, what is the performance when the enqueueoperation if you amortize the cost of resizing the array over all additions to the queue?
O(log n)
Heap Add Algorithm
O(logn) We ignore the first location of the array to ensure that parentIndex is greater than 0. Algorithm add(newEntry) // Precondition: The array heap has room for another entry newIndex = index of next available array location parentIndex = newIndex/2 //index of parent of available location while (parentIndex > 0 and newEntry > heap[parentIndex]) { heap[newIndex] = heap[parentIndex] //move parent to available location // Update indices newIndex = parentIndex parentIndex = newIndex/2 } heap[newIndex] = newEntry // Place new entry in the correct location if (the array heap is full) Double the size of the array
If the array is already sorted, what is the performance of insertion sort?
O(n)
If you implement a recursive linear search, its performance will be ____.
O(n)
In a circular array-based implementation of a queue, what is the performance when the enqueueoperation must resize the array?
O(n)
Primary Clustering
Primary clustering means that if there is a cluster and the initial position of a new record would fall anywhere in the cluster the cluster size increases. Linear probing leads to this type of clustering.
Private class TableEntry
Private class TableEntry { private k key; private v value; private boolean available; //open addressing private TableEntry next; //separate chaining }
Secondary Clustering
Secondary clustering is less severe, two records do only have the same collision chain if their initial position is the same. For example quadratic probing leads to this type of clustering.
Linear Probing Open Addressing
The average number of comparisons needed to search the probe sequence for a given key is about .5{1 + 1/(1 - λ)2} for an unsuccessful search .5{1 + 1/(1 - λ)} for a successful search The performance of hashing with linear probing degrades significantly as the load factor λ increases. To maintain reasonable efficiency, the hash table should be less than half full. That is, keep λ < 0.5
Heap sort
The implementation of heap sort begins by calling reheap repeatedly to create an initial heap from the given array. Take into account that the heap begins at index 0 instead of 1 Then the sort repeatedly removes the largest item, swaps it with the item at the end of the array, and reheaps the unsorted part of the array. O(n log n) time
Consider the getArea method shown below. public int getArea() { if (width <= 0) { return 0; } // line #1 else if (width == 1) { return 1; } // line #2 else { Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } } Assume line #1 is replaced with this line: if (width <= 0) {return width;} What will be the result?
The method will still return correct results for all non-negative width triangles.
Consider the getArea method shown below: public int getArea() { if (width <= 0) { return 0; } // line #1 else if (width == 1) { return 1; } // line #2 else { Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } } Assume the code in line #3 is changed to: Triangle smallerTriangle = new Triangle(width); This change would cause infinite recursion for which triangles?
Those with width greater than or equal to 2.
Hash Table, load factor, & Rehashing
To ensure an efficient implementation for the ADT dictionary, you must not let the load factor λ get too large You can readily compute λ and see whether it exceeds the upper limit for the particular collision resolution scheme as given in the previous note *Note: rehashing* When the load factor λ reaches its limit, since you have changed the size becomes too large, resize the hash table. To compute the table's new size, first double its present size and then increase the result to the next prime number. Use the method add to add the current entries in the dictionary to the new hash table
TreeMap vs HashMap
TreeMap: in order traversal Worst Case: O(logn) HashMap: random order worst case traversal: O(n) average case: O(1/((1-λ)^2))
A priority queue cannot have null entries
True
Each node in an ordinary linked chain references only the next node.
True
In a circular array-based implementation of a queue, the available locations are not contiguous.
True
In a circular array-based implementation of a queue, you cannot use only frontIndex to determine when a queue is full.
True
In a linked chain implementation of a queue, when both the firstNode and lastNode entries are null, the chain is empty.
True
In an array-based implementation of a queue, inserting and deleting entries is accomplished using modulo arithmetic.
True
Searching A Binary Search Tree
You can test if the search key is less than or greater than and determine then whether to go down the left or right subtree If you end up with no search tree left and haven't found what you're looking for, then the tree does not contain your entry Algorithm bstSearch(binarySearchTree, desired object) //searches a binary search tree for a given object //returns true if the object is found if (binarySearchTree is empty return false else if (desiredObject == object in the root of binarySearchTree) return true else if (desiredObject < object in the root of binarySearchTree) return bstSearch(left subtree of binarySearchTree, desired object) else return bstSearch(right subtree of binarySearchTree, desired object) Searching a binary tree of height h is O(h)
The string "eat" has ____ permutations. a. 6 b. 8 c. 4 d. 2
a. 6
When a new node is added to a linked list it is placed _____ of the chain.
at the beginning
The ____ class contains a sort method that can sort array lists.
collections
If you want to use the Comparable interface, you must implement a single method called ____.
compareTo
A _____ in Java builds an object at run time when you invoke the new operator.
constructor
It is a good practice to identify a group of _____ to implement and test before continuing with the rest of the class definition.
core methods
79) Consider the fib method from the textbook shown below: public static long fib(int n) { if (n <= 2) { return 1; // line #1 } else { return fib(n - 1) + fib(n - 2); // line #2 } } Assume line #1 is changed to this: if (n <= 2) { return 2; } How will this change affect the result of calling fib(7)? a) It will add 2 to the return from fib(7) b) It will add 4 to the return from fib(7) c) It will add 8 to the return from fib(7) d) It will double the return from fib(7)
d
Which of the following strings is a palindrome? a. "Test" b. "canal" c. "salami" d. "B"
d. "B"
____ recursion can occur when a recursive algorithm does not contain a special case to handle the simplest computations directly. a. Terminating condition b. Mutual c. Non-mutual d. Infinite
d. Infinite
Execution for a Java program starts in the _____ method.
main
Which sort algorithm starts by cutting the array in half and then recursively sorts each half?
merge sort
If an element is present in an array of length n, how many element visits, on average, are necessary to find it using a linear search?
n /2
Consider the following recursive code snippet: public static int mystery(int n, int m) { if (n <= 0) { return 0; } if (n == 1) { return m; } return m + mystery(n - 1, m); } Identify the terminating condition(s) of method mystery?
n <= 0 or n == 1
Consider the following code snippet for calculating Fibonacci numbers recursively: int fib(int n) { // assumes n >= 0 if (n <= 1) { return n; } else { return (fib(n - 1) + fib(n - 2)); } } Identify the terminating condition in this recursive method.
n <= 1
Given f(n) = 4n + 63 + 5n^2 + 3n log n what is g(n)?
n^2
A recursive method without a special terminating case would _________
never terminate.
When you add an item to a stack, you place it a.on the top b.on the bottom c.in the middle d.it doesn't matter where
on the top
When you add an item to a stack, you place it _____.
on the top
After one iteration of selection sort working on an array of 10 elements, what must hold true?
one element must be corectly placed
Retrieve the top entry from the without removing it
peek
The operation to return a stack's top entry is called a(n) a.pop b.get c.top d.peek
pop
At the time a method is called during program execution, the activation record is pushed onto the a.program stack b.execution stack c.frame d.none of the above
program stack
Suppose you wish to implement the Comparable interface to allow your Vehicle class to compare Auto objects only. Which of the following is the correct way to do this?
public class Vehicle implements Comparable <Auto>
Complete the code for the myFactorial recursive method shown below, which is intended to compute the factorial of the value passed to the method: public int myFactorial(int anInteger) { if (anInteger == 1) { return 1; } else { ______________________ } }
return (anInteger * (myFactorial(anInteger - 1)));
Complete the code for the recursive method printSum shown in this code snippet, which is intended to return the sum of digits from 1 to n: public static int printSum(int n) { if (n == 0) { return 0; } else { ______________________________ } }
return (n + printSum(n - 1));
Insert the missing code in the following code fragment. This fragment is intended to recursively compute xn, where x and n are both non-negative integers: public int power(int x, int n) { if (n == 0) { ____________________ } else { return x * power(x, n - 1); } }
return 1;
Complete the code for the recursive method shown below, which is intended to compute the sum of the first n positive integers: public int s(int n) { if (n == 1) { return 1; } else { _________________ } }
return n + s(n - 1);
The pop and peek methods throw a(n) ________ exception when the stack is empty. a.runtime b.checked c.compile time d.stackEmpty
runtime
Compression
index = hashCode % array.length
Given the following code snippet for searching an array: int[] arr = {23, 25, 29, 34, 42}; int newVal = 15; int pos = Arrays.binarySearch(arr, newVal); What value will pos have when this code is executed?
-1
In an array-based chain implementation of a Stack ADT, what value at the top of the stack indicated that it is empty?
-1
Consider the minimumPosition method from the SelectionSorter class. Complete the code to write a maximumPosition method that returns the index of the largest element in the range from index from to the end of the array. private static int minimumPosition(int[] a, int from) int minPos = from; for (int i = from + 1; i < a.length; i++) if (a[i] < a[minPos]) { minPos = i; } return minPos; private static int maximumPosition(int[] a, int from) int maxPos = from; for (int i = from + 1; i < a.length; i++) ________________ return maxPos;
(int i =0; i < a.length -1 ; i ++)
The code segment below prints some of the elements in an array with size n. Select an expression to complete the code segment so that the resulting algorithm has O(log n) running time. for __________________________ System.out.println(array[j]);
(int j = 1; j < array.length; j =j *2)
Priority Queue ADT
*high-priority-first-out* The ADT priority queue organizes objects according to their priority The form the priority takes depends on the nature of the object By making objects comparable, we can hide this detail of how the priority takes form in the objects' method compareTo
For large values of n which statement is true?
- 2n^3 + 4n^2 + 17n behaves like n^3 - 2n^3 + 4n^2 behaves like n^3 - 2n^3 behaves like n^3 - (all of the above)
Which of the following operations could be identified as the basic operation of an algorithm?
- addition - multiplication - division
The Stack ADT may be implemented with _____.
- an array - a linked-chain - a vector
A reasonable action when attempting to remove an item from an empty stack is _____.
- assume a precondition that the stack is not empty has been met - throw an exception - return null
Which of the following real-world events could be simulated using a queue?
- bank line - a shared network printer - restaurant reservation list
A "best" solution is a function of _____.
- execution time - space consumption - programming effort - (all of the above)
A fixed size array _____.
- has limited capacity - can waste memory - prevents expansion when the bag becomes full - (all of the above)
In the LinkedBag implementation, the numberOfEntries field _____.
- records the number of entries in the current bag - records the number of nodes in the chain - is set to zero in a new chain - (all of the above)
A program's execution time depends in part on _____.
- the speed of the computer it is running on - the memory capacity - the language the algorithm is written in - (all of the above)
Which one of the following would not be considered to be a basic operation?
- variable initialization - simple assignment - operations to control loop execution
The performance of an algorithm is most closely related to what?
...
What is the sequence of values in b after the following code is executed? int[] b = {1, 2, 3, 4, 5}; for (int i = 0; i < b.length; i++) int j = b.length - 1 - i; int temp = b[i]; b[i] = b[j]; b[j] = temp;
1,2,3,4,5
short
16 bits
Consider the following recursive code snippet: public int mystery(int n, int m) { if (n == 0) { return 0; } if (n == 1) { return m; } return m + mystery(n - 1, m); } What value is returned from a call to mystery(3,6)?
18
Using the evaluatePostfix algorithm, evaluate the following postfix expression. wx+ y* z/ Assume that w=3 , x=4, y = 2, z = 7. a.2 b.28 c.18 d.21
2
Given int[] list = {5, 1, 6, 4, 2, 7, 3}, what are the contents of list after the partitioning phase of Quicksort if the middle element is chosen as the pivot?
3,1,2,4,6,7,5
An array contains 3, 6, 4, 1, 5, 2, in that order. Selection Sort is used to sort it in ascending order. What is the order of elements after the first three passes (through the outer loop)?
3,2,1,4,5,6
float
32 bits
int
32 bits
Using the evaluatePostfix algorithm, evaluate the following postfix expression. 7 2 + 4 * a.36 b.13 c.15 d.18
36
Consider the following recursive code snippet: public int mystery(int n, int m) { if (n == 0) { return 0; } if (n == 1) { return m; } return m + mystery(n - 1, m); } What value is returned from a call to mystery(1,5)?
5
long
64 bits
Consider the recursive method myPrint: public void myPrint(int n) { if (n < 10) { System.out.print(n); } else { int m = n % 10; System.out.print(m); myPrint(n / 10); } } What is printed for the call myPrint(8)?
8
How many recursive calls to the fib method shown below would be made from an original call to fib(4)? (Do not count the original call) public int fib(int n) { // assumes n >= 0 if (n <= 1) { return n } else { return (fib(n - 1) + fib(n - 2)); } }
8
byte
8 bits
The effect of doubling the input size on an algorithm with time complexity O(n^3) is _____.
8 times
The Java Class Library interface Queue method to put an entry on the back of a queue that returns false if the method fails is a. offer b. add c. put d. poll
A
The Java Class Library interface Queue method that retrieves the entry at the front of a queue but throws a NoSuchElementException if the queue was empty is a. empty b. peek c. poke d. look
A
A common alias for the queue method getFront is a. peek b. get c. put d. all of the above
A
A linked chain whose last node is null is sometimes called a(n) a. linear linked chain b. circular linked chain c. null terminated linked chain d. all of the above
A
After the following statements execute, what item is at the back of the queue? QueueInterface<String> zooDelivery = new LinkedQueue<>(); zooDelivery .enqueue("lion"); zooDelivery .enqueue("tiger"); zooDelivery .enqueue("cheetah"); String next = zooDelivery .dequeue(); next = zooDelivery .dequeue(); zooDelivery .enqueue("jaguar"); a. "jaguar" b. "cheetah" c. "tiger" d. "lion"
A
After the following statements execute, what item is at the front of the queue? QueueInterface<String> zooDelivery = new LinkedQueue<>(); zooDelivery .enqueue("lion"); zooDelivery .enqueue("tiger"); zooDelivery .enqueue("cheetah"); String next = zooDelivery .dequeue(); next = zooDelivery .dequeue(); zooDelivery .enqueue("jaguar"); a. "cheetah" b. "jaguar" c. "tiger" d. "lion"
A
An array whose index of the first location follows the index its last one is call a. circular b. following c. round d. oval
A
How can we tell if a two-part circular linked chain queue is empty? a. both the queueNode and freeNode reference the same node b. the freeNode is one node behind the queueNode c. the freeNode is one node in front of the queueNode d. the empty field is set to true
A
How does a queue organize it items? a. according to the order in which they were added b. by priority c. alphabetically d. randomly
A
In a ______ the last node references the first node. a. circular linked chain b. array based queue c. array based circular queue d. linked chain
A
In a circular array-based implementation of a queue implementation where one unused location is used to differentiate between the front and back of the queue, the frontIndex is _____ than the backIndex. a. two more b. one more c. one less d. two less
A
In a circular array-based implementation of a queue, the initial size of the array should be a. one more than the queue's initial capacity b. one less than the queue's initial capacity c. two more than the queue's initial capacity d. two less than the queue's initial capacity
A
In a circular array-based implementation of a queue, what is the performance when the dequeue operation ? a. O(1) b. O(log n) c. O(n) d. O(n2)
A
In a circular array-based implementation of a queue, what is the performance when the enqueue operation if you amortize the cost of resizing the array over all additions to the queue? a. O(1) b. O(log n) c. O(n) d. O(n2)
A
In a circular linked chain, when a node is removed from the queue a. it is deallocated b. it is moved to a separate list c. it is ignored d. none of the above
A
In a doubly linked chain implementation of a queue, what is the performance when the dequeue operation? a. O(1) b. O(log n) c. O(n) d. O(n^2)
A
In a linked chain implementation of a queue, an external reference to the last node in the chain is called a(n) a. tail reference b. last node c. linked reference d. final node
A
In a linked chain implementation of a queue, the performance of the enqueue operation is a. O(1) b. O(log n) c. O(n) d. O(n^2)
A
In a linked chain implementation of a queue, the performance of the getFront operation is a. O(1) b. O(log n) c. O(n) d. O(n2)
A
In a two-part circular linked chain implementation of a queue, what is the performance when the dequeue operation ? a. O(1) b. O(log n) c. O(n) d. O(n^2)
A
In an array-based implementation of a queue, a possible solution to dealing with the full condition is to a. leave one array location unused b. check for frontIndex equal to backIndex c. wait for an arrayFullExcetion to be thrown d. all of the above
A
In an array-based implementation of a queue, a possible solution to dealing with the full condition is to a. maintain a count of queue items b. check for frontIndex equal to backIndex c. wait for an arrayFullExcetion to be thrown d. all of the above
A
In the linked chain implementation of a queue, the chain's first node contains a. the queue's front entry b. the queue's back entry c. both a & b d. none of the above
A
In the linked chain implementation of a queue, the chain's tail last node contains a. the queue's back entry b. the queue's front entry c. both a & b d. none of the above
A
The ADT priority queue organizes objects a. according to priority of the objects b. alphabetically c. from front to back d. from back to front
A
The Java Class Library interface Queue method that retrieves and removes the entry at the front of a queue and returns null if the queue was empty is a. poll b. remove c. retrieve d. get
A
The Java Class Library interface Queue method that retrieves and removes the entry at the front of a queue and throws a NoSuchElementException if the queue was empty is a. remove b. poll c. retrieve d. get
A
The Java Class Library interface Queue method that retrieves the entry at the front of a queue but returns null if the queue was empty is a. peek b. empty c. poke d. look
A
What item is at the front of the list after these statements are executed? DequeInterface<String> waitingLine = new LinkedDeque<>(); waitingLine.addToFront("Jack"); waitingLine.addToFront("Rudy"); waitingLine.addToBack("Larry"); waitingLine.addToBack("Sam"); String name = waitingLine.getBack(); a. Rudy b. Jack c. Larry d. Sam
A
What type of behavior defines a queue? a. first-in first-out b. first-in last-out c. last-in first-out d. none of the above
A
When a counter enumerates simulated time units, it is called a(n) a. time-driven simulation b. clock simulation c. event-driven simulation d. all of the above
A
When a linked chain contain nodes that reference both the next node and the previous node, it is called a(n) a. doubly linked chain b. ordinary chain c. multi-linked chain d. two-way linked chain
A
When would you choose a two-part circular chain over a circular chain? a. when you frequently add an entry after removing one b. when you rarely add entries after removing one c. when you are space constrained d. when you don't want the garbage collector running
A
Where does a queue add new items? a. at the back b. at the front c. in the middle d. randomly
A
Where will you find the item added earliest to a queue? a. at the front b. at the back c. in the middle d. randomly
A
Set ADT
A collection that contains no duplicate elements.
Balanced
A tree whose subtrees differ in height by no more than 1
True or false? (a) Both Arrays and Collections classes belong to the java.util package. (b) Arrays has overloaded methods for sorting an array of integers, doubles, or strings. (c) Arrays uses the Selection Sort algorithm for sorting. (d) Arrays has overloaded methods for filling the elements of an array with a given value. (e) All methods in the Arrays class are static.
A)T B)T C)F D)T E)T
Reheap Algorithm
Algorithm reheap(rootIndex) // Transforms the semiheap rooted at rootIndex into a heap done = false orphan = heap[rootIndex] while (!done and heap[rootIndex] has a child) { largerChildIndex = index of the larger child of heap[rootIndex] if (orphan < heap[largerChildIndex] { heap[rootIndex] = heap[largerChildIndex] rootIndex = largerChildIndex } else done = true } heap[rootIndex] = orphan
The Java Class Library method to resize an array is called _____.
Arrays.copyOf
Assume that names is an array of String objects that has been initialized with a large number of elements. Select the statement that would sort the elements in names in ascending alphabetic order.
Arrays.sort(names);
A common alias for the queue method dequeue is a. get b. remove c. delete d. all of the above
B
A common alias for the queue method enqueue is a. put b. add c. insert d. all of the above
B
In a circular array-based implementation of a queue, what is the performance when the enqueue operation must resize the array? a. O(n^2) b. O(n) c. O(log n) d. O(1)
B
What item is at the front of the list after these statements are executed? DequeInterface<String> waitingLine = new LinkedDeque<>(); waitingLine.addToFront("Jack"); waitingLine.addToFront("Rudy"); waitingLine.addToBack("Larry"); waitingLine.addToBack("Sam"); String name = waitingLine.getFront(); a. Jack b. Rudy c. Larry d. Sam
B
When adding a node to a two-part circular linked chain implementation of a queue we insert the new node into the chain a. after the node that freeNode references b. before the node that freeNode references c. it has nothing to do with the location of freeNode d. none of the above
B
A two-part circular linked chain implementation of a queue a. is initialized with no available nodes b. keeps nodes that are deallocated for future use c. allocates new nodes on demand when there are no available nodes d. all of the above
C
If we use a chain of linked nodes with only a head reference to implement a queue which statement is true? a. You must traverse the entire chain to access the last node. b. Accessing the last node is very inefficient. c. Both a & b d. None of the above
C
In a linked chain implementation of a queue, when the queue is empty a. the firstNode is null b. the lastNode is null c. both a & b d. none of the above
C
In order to modify the front entry of a queue a. you need a set method defined b. you need to dequeue the front entry, modify the contents, and then use the requeue method to place it back on the front of the queue c. you cannot modify it under any circumstances d. none of the above
C
What item is at the front of the list after these statements are executed? DequeInterface<String> waitingLine = new LinkedDeque<>(); waitingLine.addToBack("Adam"); waitingLine.addToFront("Rudy"); waitingLine.addToBack("Larry"); waitingLine.addToBack("Sam"); waitingLine.addtoFront("Jack"); String name = waitingLine.getFront(); name = getFront(); a. Adam b. Rudy c. Jack d. Sam
C
When adding a node to a two-part circular linked chain implementation of a queue a. first check if a node is already available in the chain b. check to see if the linked chain needs resized c. allocate a new node and assign the reference to freeNode d. all of the above
C
An array whose index of the first location follows the index its last one is call
Circular
The sort method of the Arrays class sorts arrays containing objects of classes that implement the ____ interface.
Comparable
Map/Dictionary ADT
Contains entries that are key-value pairs organized by their search keys. A map cannot contain duplicate keys; each key can map to at most one value You can add a new entry, and you can locate, retrieve, or remove an entry, given its search key. In addition, you can traverse a dictionary's search keys or values.
A deque ADT behaves a. like a queue b. like a stack c. both a & b d. none of the above
D
A two-part circular linked chain implementation of a queue a. conceptually has two lists b. uses a freeNode reference for the first available node that follows the queue c. has nodes that form the queue followed by nodes that are available for use in the queue d. all of the above
D
In a two-part circular linked chain implementation of a queue a. queueNode references the front node of the queue b. freeNode references the node that follows the queue c. the queue is empty if queueNode equals freeNode d. all of the above
D
The dequeue method a. throws an exception if the queue is empty b. returns the item at the front of the queue c. removes the item at the front of the queue d. all of the above
D
What item is at the front of the list after these statements are executed? DequeInterface<String> waitingLine = new LinkedDeque<>(); waitingLine.addToFront("Jack"); waitingLine.addToBack("Rudy"); waitingLine.addToBack("Larry"); waitingLine.addToFront("Sam"); String name = waitingLine.getFront(); name = getBack(); waitingLine.addtoBack("Adam"); a. Jack b. Rudy c. Adam d. Sam
D
When removing a node from a two-part circular linked chain implementation of a queue a. the entry at the front of the queue is returned b. the node is moved to the part of the chain that is available for the enqueue method c. the queueNode is advanced d. all of the above
D
Which of the following real-world events could be simulated using a queue? a. bank line b. a shared network printer c. restaurant reservation list d. all of the above
D
Heap - A Priority Queue Implementation
For heaps, we implement the ADT priority queue A heap is a complete binary tree whose nodes contain Comparable objects and are organized as follows: - Each node contains an object that is no smaller (or no larger) than the objects in its descendants. *Guarantees O(logn) for both add() and remove()* In a maxheap, the object in a node is greater than or equal to its descendant objects The subtrees of a maxheaps are also maxheaps Unlike a binary search tree, however, no relationship exists between the subtrees of a node in a heap A heap has operations that retrieve and remove the objects in its root: removeMax, getMax
If a call to the Arrays static method binarySearch returns a value of -10, what can be concluded? I the element is not in the array II the element is at index 10 III the element can be inserted at index 9
I and III
Which of the following classes implement the Comparable interface? I Date II Collections III String
I and III
Which statement(s) about recursion are true? I Recursion is faster than iteration. II Recursion is often easier to understand than iteration. III Recursive design has an economy of thought.
II and III only
Which of the following executions represent mutual recursion? I method E calls method T, which calls method F II method E calls method T, which calls method F, which calls method E III method F calls method F
II only
Hashing: Quadratic Probing
In Quadratic probing, you increment where you are looking by the squares of numbers. If you are index i, you then look at i + 1^2, then i + 2^2, then i + 3^2...
Hashing: open addressing vs. separate chaining
In open addressing, when a collisions occurs (the space you want to put an item is already hashed to another item), you look for the next available space to put your item in. Pros: **Con1: a hash table may end up with no locations that contain null, regardless of how few or many entries are in the dictionary** Con2: leads to more rehashing than SepChain --> larger table In separate chaining, when a collision occurs, you link another item onto the first item or chain of multiple items. Pro1: Separate chaining is generally faster than open addressing Pro2: since λ can be larger, you have a smaller hash table Cons: require more memory: each location is a chain of linked nodes
Consider the code for the recursive method mysteryPrint shown in this code snippet: public static int mysteryPrint(int n) { if (n == 0) { return 0; } else { return (n + mysteryPrint(n-1)); } } What will be printed with a call to mysteryPrint (-4)? a. -10 b. 0 c. -22 d. Nothing - a StackoverflowError exception will occur
NOT a. -10 NOT c. -22
____ recursion can occur when a recursive algorithm does not contain a special case to handle the simplest computations directly.
Infinite
What is an advantage of using a chain for a Bag ADT?
It avoids moving data when adding or removing bag entries.
Given the following code snippet: public static int newCalc(int n) { if (n < 0) { return -1; } else if (n < 10) { return n; } else { return (n % 10) + newCalc(n / 10); } } What value will be returned when this code is executed with a call to newCalc(15)? a. 2.5 b. 6.5 c. 2 d. 6
NOT a. 2.5 NOT c. 2
Consider the following change to the PermutationGenerator class from the textbook. Instead of adding the removed character to the front of the each permutation of the simpler word, we will add it to the end. // Add the removed character to the end of // each permutation of the simpler word for (String s : shorterWordPermutations) { result.add(s + word.charAt(i)); } Consider the list produced by the modified PermutationGenerator. Which best describes this list? a. It is an incomplete list of permutations. b. It contains reversed permutations. c. It contains all permutations. d. It contains strings that are not permutations.
NOT a. It is an incomplete list of permutations. NOT d. It contains strings that are not permutations.
Consider the getArea method from the textbook shown below: public int getArea() { if (width <= 0) { return 0; } // line #1 if (width == 1) { return 1; } // line #2 Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } If line #1 was eliminated from the method, what would be the result when calling getArea? a. We would lose our only recursive case. b. A negative or zero width would cause problems. c. Nothing - the method would still work correctly. d. A positive width would reduce the correct area by 1.
NOT a. We would lose our only recursive case.
Question 2 1 pts Suppose we wrote a new version of method fib, called newFib. Compare newFib to the original fib shown below: public static long newFib(int n) { if (n <= 3) { return 1; } else { return newFib(n - 1) + newFib(n - 2) + newFib(n - 3); } } public static long fib(int n) { if (n <= 2) { return 1; } else { return fib(n - 1) + fib(n - 2); } } For which values of the integer n does newFib(n) always returns a value greater than fib(n)? a. any positive n b. n >= 3 c. n > 3 d. any value of n
NOT a. any positive n
Consider the getArea method from the textbook shown below: public int getArea() { if (width <= 0) { return 0; } // line #1 if (width == 1) { return 1; } // line #2 Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } Assume line #3 is changed to this: Triangle smallerTriangle = new Triangle(width + 1) When calling the getArea method on a Triangle object with width = 4, what result will be produced? a. area will only be incorrect for a triangle objects with width = 1 b. area for all triangles will be computed to be too low c. infinite recursion will occur for triangle objects with width >= 2 d. area for all triangles will be computed to be too high
NOT a. area will only be incorrect for a triangle objects with width = 1 NOT d. area for all triangles will be computed to be too high
Complete the following code snippet, which is intended to print out all permutations of the string generate by using a permutation generator object. public class PermutationGeneratorTester { public static void main(String[] args) { PermutationGenerator generator = new PermutationGenerator("generate"); ArrayList<String> permutations = generator.getPermutations(); for (String s : permutations) { ____________________ } } } a. generator.setPermutations(); b. generator.calculate(); c. generator.print(); d. System.out.println(s);
NOT a. generator.setPermutations();
Consider the following code snippet for recursive addition: int add(int i, int j) { // assumes i >= 0 if (i == 0) { return j; } else { return add(i - 1, j + 1); } } Identify the terminating condition in this recursive method. a. if (i == 0) b. there is no terminating condition c. return j d. return add(i - 1, j + 1)
NOT a. if (i == 0) NOT d. return add(i - 1, j + 1)
Consider the getArea method from the textbook shown below. public int getArea() { if (width <= 0) { return 0; } // line #1 else if (width == 1) { return 1; } // line #2 else { Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } } Where is/are the terminating condition(s)? a. line #1 b. lines #1 and #2 c. line #4 d. line #2
NOT a. line #1
Consider the following recursive code snippet: public static int mystery(int n, int m) { if (n <= 0) { return 0; } if (n == 1) { return m; } return m + mystery(n - 1, m); } Identify the terminating condition(s) of method mystery? a. n <= 0 b. n == 1 c. n > 0 d. n <= 0 or n == 1
NOT a. n <= 0
Backtracking _____. a. never abandons a partial solution. b. starts from the end of the program and works backward to the beginning. c. starts with a partial solution and builds it up to get closer to the goal. d. explores only one path toward a solution
NOT a. never abandons a partial solution. NOT b. starts from the end of the program and works backward to the beginning.
Consider the method below, which displays the characters from a String in reverse order. Each character appears on a separate line. Select the statement that should be used to complete the method, so that it performs a recursive method call correctly. public static void printReverse(String word) { if (word.length() > 0) { ___________________________ System.out.println(word.charAt(0)); } } a. printReverse(word.length() - 1); b. printReverse(new String(word.charAt(1))); c. printReverse(word); d.printReverse(word.substring(1));
NOT a. printReverse(word.length() - 1); NOT b. printReverse(new String(word.charAt(1)));
Complete the code for the myFactorial recursive method shown below, which is intended to compute the factorial of the value passed to the method: public int myFactorial(int anInteger) { if (anInteger == 1) { ______________________ } else { return (anInteger * myFactorial(anInteger - 1)); } } a. return 0; b. return myFactorial(anInteger); c. return -anInteger; d. return 1;
NOT a. return 0;
Consider the getArea method from the textbook shown below. public int getArea() { if (width <= 0) { return 0; } // line #1 if (width == 1) { return 1; } // line #2 Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } Assume that line #2 is changed to this: if (width == 1) { return 2; } How would this affect calls to getArea? a. It would make no difference to any call. b. It would double every triangle area. c. It would add 1 to all calls except those where width <= 0. d. It would subtract 1 from all calls.
NOT b. It would double every triangle area.
Consider the getArea method from the textbook shown below. public int getArea() { if (width <= 0) { return 0; } // line #1 else if (width == 1) { return 1; } // line #2 else { Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } } Assume line #1 is replaced with this line: if (width <= 0) {return width;} What will be the result? a. The method will still return correct results for all non-negative width triangles. b. The method will return area to be one too high for all triangles. c. The method will return incorrect results for triangles with width equal to 0. d. The method will return incorrect results for triangles with width equal to 1.
NOT b. The method will return area to be one too high for all triangles.
Consider the getArea method from the textbook shown below: public int getArea() { if (width <= 0) { return 0; } // line #1 Triangle smallerTriangle = new Triangle(width - 1); // line #2 int smallerArea = smallerTriangle.getArea(); // line #3 return smallerArea + width; // line #4 } If line#1 was removed, what would be the result? a. The recursive method would correctly calculate the area of the original triangle. b. The recursive method would terminate when the width reached 0. c. The recursive method would cause an exception for values below 0. d. The recursive method would construct triangles whose width was negative.
NOT b. The recursive method would terminate when the width reached 0.
A palindrome is a word or phrase spelled which reads the same forward or backward. Consider the following code snippet: public boolean palindrome(String string) { return isPal(string, 0, string.length() - 1); } private boolean isPal(String string, int left, int right) { if (left >= right) { return true; } else if (string.charAt(left) == string.charAt(right)) { return isPal(string, left + 1, right - 1); } else { return false; } } What does the method palindrome return? a. the Boolean value returned from the isPal method b. false c. true d. a palindrome not found exception
NOT b. false
Consider the recursive square method shown below. It takes a non-negative int argument. Then it recursively adds the number n to itself n times to produce the square of n. Complete the correct code for the square helper method. public int square(int n) { ____________________; } public int square(int c, int n) { if (c == 1) { return n; } else { return n + square(c - 1, n); } } a. return square(n, n) b. return square(n, n - 1) c. return square(n - 1, n) d. return square(n)
NOT b. return square(n, n - 1) NOT c. return square(n - 1, n)
Consider the recursive version of the fib method from the textbook shown below: public static long fib(int n) { if (n <= 2) { return 1; } else { return fib(n - 1) + fib(n - 2); } } How many total recursive calls (not counting the original call) to fib will be made from the original call of fib(7)? a. 12 b. 30 c. 32 d. 24
NOT c. 32
Consider the recursive method shown below: public static int strangeCalc(int bottom, int top) { if (bottom > top) { return -1; } else if (bottom == top) { return 1; } else { return bottom * strangeCalc(bottom + 1, top); } } What value will be returned with a call to strangeCalc(2,3)? a. 24 b. 1 c. 6 d. 2
NOT c. 6
Why does the best recursive method usually run slightly slower than its iterative counterpart? a. Testing the terminating condition takes longer. b. Each recursive method call takes processor time. c. Checking multiple terminating conditions take more processor time. d. Multiple recursive cases must be considered.
NOT c. Checking multiple terminating conditions take more processor time. NOT d. Multiple recursive cases must be considered.
Consider the method powerOfTwo shown below: public boolean powerOfTwo(int n) { if (n == 1) // line #1 { return true; } else if (n % 2 == 1) // line #2 { return false; } else { return powerOfTwo(n / 2); // line #3 } } How many recursive calls are made from the original call powerOfTwo(63) (not including the original call)? a. 0 b. 6 c. 4 d. 1
NOT d. 1
Consider the recursive method myPrint in this code snippet: public void myPrint(int n) { if (n < 10) { System.out.print(n); } else { int m = n % 10; System.out.print(m); myPrint(n / 10); } } What is printed for the call myPrint(821)? a. 10 b. 128 c. 821 d. 12
NOT d. 12
Consider the recursive version of the fib method from the textbook shown below: public static long fib(int n) { if (n <= 2) { return 1; } else { return fib(n - 1) + fib(n - 2); } } How many total recursive calls (not counting the original call) to fib will be made from the original call of fib(6)? a. 14 b. 20 c. 6 d. 12
NOT d. 12
Consider the iterative version of the fib method from the textbook shown below: public static long fib(int n) { if (n <= 2) { return 1; } long fold = 1; long fold2 = 1; long fnew = 1; for (int i = 3; i <= n; i++) { fnew = fold + fold2; fold2 = fold; fold = fnew; } return fnew; } How many iterations of the for loop will there be for the call fib(6)? a. 6 b. 4 c. 3 d. 5
NOT d. 5
Consider the getArea method from the textbook shown below: public int getArea() { if (width <= 0) { return 0; } // line #1 Triangle smallerTriangle = new Triangle(width - 1); // line #2 int smallerArea = smallerTriangle.getArea(); // line #3 return smallerArea + width; // line #4 } If line#1 was removed, what would be the result? a. The recursive method would terminate when the width reached 0. b. The recursive method would construct triangles whose width was negative. c. The recursive method would correctly calculate the area of the original triangle. d. The recursive method would cause an exception for values below 0.
NOT d. The recursive method would cause an exception for values below 0.
Complete the following code snippet, which is intended to be a recursive method that reverses a String value: public static String reverseIt(String s) { if (s.length() <= 1) { _________ } else { return reverseIt(s.substring(1)) + s.charAt(0); } } a. return s; b. return s.substring(1); c. return 0; d. return s.charAt(0);
NOT d. return s.charAt(0);
Consider the code for the recursive method mystery shown in this code snippet: public static int mystery(int n) { if (n == 0) { return 0; } else { return (n + mystery(n-1)); } } What will be printed by the statement System.out.println(mystery(-4));?
Nothing - a StackoverflowError exception will occur
A _____ is thrown when you access a reference that is null.
NullPointerException
If an algorithm requires 7 basic operations for an algorithm with a problem size of n, the algorithmic complexity is _____.
O(1)
In a circular array-based implementation of a queue, what is the performance when the dequeue operation ?
O(1)
In a circular array-based implementation of a queue, what is the performance when the enqueueoperation does not resize the array?
O(1)
In a doubly linked chain implementation of a queue, what is the performance when the dequeue operation ?
O(1)
In a linked chain implementation of a queue, the performance of the enqueue operation is
O(1)
In a linked chain implementation of a queue, the performance of the enqueue operation is _____.
O(1)
In a linked chain implementation of a queue, the performance of the getFront operation is
O(1)
In a linked-chain implementation of a Stack ADT, the performance of looking at the first entry on the stack without removing it is _____.
O(1)
In a linked-chain implementation of a Stack ADT, the performance of pushing an entry onto the stack is _____.
O(1)
In a two-part circular linked chain implementation of a queue, what is the performance when the dequeue operation ?
O(1)
In an array-based chain implementation of a Stack ADT, what is the performance of the ensureCapacity method when the array is full?
O(n)
In Big-Oh notation, selection sort is a(n) ____ algorithm.
O(n^2)
In a circular array-based implementation of a queue, what is the performance when the enqueue operation must resize the array?
O(n^2)
The selection sort requires _____ comparisons for an array of n items
O(n^2)
Hashing: Double Hashing
Resolves a collision during hashin by examining locations in the hash table at the original hash index plus an increment defined by a second hash function. The second hash function should: - Differ from the first hash function - Depend on the search key - Have a nonzero value Reaches every location in the hash able, if the size of the table is a prime number. Avoids both primary cluster and secondary clustering Double hashing uses a second has function to compute these increments in a key-dependent way to avoid both primary and secondary clustering.
The largestPosition method below returns the index of the largest element in the tail range of an array of integers. Select the expression that would be needed to complete the selectionSort method below, so that it sorts the elements in descending order. Finds the largest element in the tail range of an array. @param a the array to be searched @param from the first position in a to compare @return the position of the largest element in range a[from]..a[a.length - 1] private static int largestPosition(int[] a, int from) int maxPos = from; for (int j = from + 1; j < a.length; j++) if (a[j] > a[maxPos]) maxPos = j; return maxPos; public static void selectionSort(int[] a) for ____________________________________ int maxPos = largestPosition(a, i); ArrayUtil.swap(a, maxPos, i);
System.currentTimeMillis() - start
The Java Class Library ADT PriorityQueue uses the compareTo method to determine how to order entries.
True
The Java Class Library interface for Queue has no operation to modify the contents of the front entry.
True
The Queue interface extends the Deque interface.
True
The item most recently added to a queue is at the back of the queue.
True
The null value can be used to signal failure to remove or retrieve an entry from a priority queue when it is empty.
True
When a circular linked chain is used to represent a queue, it is not necessary to maintain a firstNode data field.
True
You can push, pop and get items at either end of the ADT deque.
True
You need two external references for a circular doubly linked chain, one for the firstNode and one for the lastNode.
True
In a vector implementation of a Stack ADT, you add an entry to the top of a stack using which vector method?
add
If we use a chain of linked nodes with only a head reference to implement a queue which statement is true?
You must traverse the entire chain to access the last node and accessing the last node is very inefficient.
101) Consider the following change to the PermutationGenerator class from the textbook. Instead of adding the removed character to the front of the each permutation of the simpler word, we will add it to the end. // Add the removed character to the end of // each permutation of the simpler word for (String s : shorterWordPermutations) { result.add(s + word.charAt(i)); } Consider the list produced by the modified PermutationGenerator. Which best describes this list? a) It contains all permutations. b) It contains reversed permutations. c) It is an incomplete list of permutations. d) It contains strings that are not permutations.
a
104) Consider the mutually recursive methods below. Select the method call that could be used to generate the output sequence: A5 B4 A3 B2 A1 public static void methodA(int value) { if (value > 0) { System.out.print(" A" + value); methodB(value - 1); } } public static void methodB(int value) { if (value > 0) { System.out.print(" B" + value); methodA(value - 1); } } a) methodA(5); b) methodB(5); c) methodA(4); d) methodB(4);
a
21) Insert the missing code in the following code fragment. This fragment is intended to recursively compute xn, where x and n are both non-negative integers: public int power(int x, int n) { if (n == 0) { ____________________ } else { return x * power(x, n - 1); } } a) return 1; b) return x; c) return power(x, n - 1); d) return x * power(x, n - 1);
a
28) When a recursive method is called, and it does not perform recursion, what must be true? a) The terminating condition was true. b) One recursive case condition was true. c) All recursive case conditions were true. d) An exception will occur in the method.
a
29) Consider the getArea method from the textbook shown below. public int getArea() { if (width <= 0) { return 0; } // line #1 if (width == 1) { return 1; } // line #2 Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } Assume that line #2 is changed to this: if (width == 1) { return 2; } How would this affect calls to getArea? a) It would add 1 to all calls except those where width <= 0. b) It would make no difference to any call. c) It would double every triangle area. d) It would subtract 1 from all calls.
a
32) Consider the getArea method from the textbook shown below: public int getArea() { if (width <= 0) { return 0; } // line #1 if (width == 1) { return 1; } // line #2 Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } If line #1 was eliminated from the method, what would be the result when calling getArea? a) A negative or zero width would cause problems. b) Nothing - the method would still work correctly. c) We would lose our only recursive case. d) A positive width would reduce the correct area by 1.
a
34) Would switching the special case order affect the return value of the following method? public int mystery(int n, int m) { if (n == 0) // special case #1 { return 0; } if (n == 1) // special case #2 { return m; } return m + mystery(n - 1, m); } a) No b) Yes c) It is impossible to tell. d) An exception will be thrown.
a
35) Which of the following options could be used as a terminating condition for a recursive method that finds the middle character of a String with any number of characters? I the length of the String is 1 II first and last String characters match III the String is not empty a) I b) II c) I, II and III d) I and III
a
37) Consider the method below, which implements the exponentiation operation recursively. Select the statement that should be used to complete the method, so that it handles the special case correctly. public static double power(int base, int exponent) { if (exponent == 0) { _______________ } else { reurn base * power(base, exponent - 1); } } a) return 1; b) return base; c) return 0; d) return 1 * power(base, exponent - 1);
a
40) Consider the method powerOfTwo shown below: public boolean powerOfTwo(int n) { if (n == 1) // line #1 { return true; } else if (n % 2 == 1) // line #2 { return false; } else { return powerOfTwo(n / 2); // line #3 } } What is the best interpretation of line #1? a) One is a power of two b) One is not a power of two c) Any multiple of one is a power of two d) 1 is an invalid choice for n
a
44) Complete the code for the myFactorial recursive method shown below, which is intended to compute the factorial of the value passed to the method: public int myFactorial(int anInteger) { _____________________________ { return 1; } else { return(anInteger * myFactorial(anInteger - 1)); } } a) if (anInteger == 1) b) if ((anInteger - 1) == 1) c) if (anInteger * (anInteger - 1) == 1) d) if (myFactorial(anInteger) == 1)
a
47) Complete the code for the calcPower recursive method shown below, which is intended to raise the base number passed into the method to the exponent power passed into the method: public static int calcPower(int baseNum, int exponent) { int answer = 0; ________________________ { answer = 1; } else { answer = baseNum * calcPower (baseNum, exponent - 1); } return answer; } a) if (exponent == 0) b) if (exponent == 1) c) if (exponent == -1) d) if (exponent != 1)
a
5) Consider the getArea method from the book shown below. public int getArea() { if (width <= 0) { return 0; } // line #1 else if (width == 1) { return 1; } // line #2 else { Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } } Assume lines #1 and #2 were changed to this: if (width == 1) { return 1; } // new line #1-2 What will happen when this code is executed? a) A negative or zero width would cause problems. b) Nothing - the method would still be correct. c) We would lose our only recursive case. d) A positive width would reduce the correct area by 1.
a
56) Given the following code snippet: public static int newCalc(int n) { if (n < 0) { return -1; } else if (n < 10) { return n; } else { return (1 + newCalc(n / 10)); } } What value will be returned when this code is executed with a call to newCalc(15)? a) 2 b) 2.5 c) 5 d) 5.5
a
59) Complete the following code snippet, which is intended to be a recursive method that will find the smallest value in an array of double values from index to the end of the array: public static double minVal(double[] elements, int index) { if (index == elements.length - 1) { __________________ } double val = minVal(elements, index + 1); if (elements[index] < val) { return elements[index]; } else { return val; } } a) return elements[index]; b) return 1; c) return 0; d) return elements[0];
a
6) Consider the getArea method from the textbook shown below. public int getArea() { if (width <= 0) { return 0; } // line #1 else if (width == 1) { return 1; } // line #2 else { Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } } Assume line #1 is replaced with this line: if (width <= 0) {return width;} What will be the result? a) The method will still return correct results for all non-negative width triangles. b) The method will return incorrect results for triangles with width equal to 0. c) The method will return incorrect results for triangles with width equal to 1. d) The method will return area to be one too high for all triangles.
a
61) Complete the following code snippet, which is intended to be a recursive method that will find the sum of all elements in an array of double values from index to the end of the array: // return the sum of all elements in arr[] public static double findSum(double arr[], int index) { if (index == 0) { _____________________ } else { return (arr[index] + findSum(arr, index - 1)); } } Assume that this method would be called using an existing array named myArray as follows: findSum(myArray,myArray.length - 1); a) return arr[index]; b) return arr[index + 1]; c) return arr[1]; d) return arr[index - 1];
a
62) Complete the following code snippet, which is intended to be a recursive method that reverses a String value: public static String reverseIt(String s) { if (s.length() <= 1) { _________ } else { return reverseIt(s.substring(1)) + s.charAt(0); } } a) return s; b) return 0; c) return s.charAt(0); d) return s.substring(1);
a
68) A palindrome is a word or phrase that reads the same forward or backward. Consider the following code snippet: public boolean palindrome(String string) { return isPal(string, 0, string.length() - 1); } private boolean isPal(String string, int left, int right) { if (left >= right) { return true; } else if (string.charAt(left) == string.charAt(right)) { return isPal(string, left + 1, right - 1); } else { return false; } } What does the condition left >= right refer to? a) An empty or one-character string is considered a palindrome. b) The string is not a palindrome. c) It cannot be determined if the string is a palindrome. d) You have reached the middle of the string.
a
7) Consider the following code snippet for recursive addition: int add(int i, int j) { // assumes i >= 0 if (i == 0) { return j; } else { return add(i - 1, j + 1); } } Identify the terminating condition in this recursive method. a) if (i == 0) b) return j c) return add(i - 1, j + 1) d) there is no terminating condition
a
70) Consider the recursive square method shown below. It takes a non-negative int argument. Then it recursively adds the number n to itself n times to produce the square of n. Complete the correct code for the square helper method. public int square(int n) { ____________________; } public int square(int c, int n) { if (c == 1) { return n; } else { return n + square(c - 1, n); } } a) return square(n, n) b) return square(n) c) return square(n - 1, n) d) return square(n, n - 1)
a
_____ is an advantage of using an array to implement the ADT bag.
adding an entry to a bag is fast
71) Consider the recursive square method shown below that takes a non-negative int argument: public int square(int n) { return square(n, n); } public int square(int c, int n) { if (c == 1) { return n; } else { return n + square(c - 1, n); } } Assume that the last return statement is changed to this: return square(c - 1, n); What would a call to square(7) return? a) 7 b) 13 c) 14 d) 49
a
77) Consider the fib method from the textbook shown below: public static long fib(int n) { if (n <= 2) { return 1; } else { return fib(n - 1) + fib(n - 2); }} Computing the 7th fibonacci number, fib(7), recursively computes fib(6), fib(5), and fib(4) ___ times respectively. a) 1, 2, and 3 b) 6, 5, and 4 c) 4, 5, and 6 d) 3, 2, and 1
a
86) The method below implements the exponentiation operation recursively by taking advantage of the fact that, if the exponent n is even, then xn = (xn/2)2. Select the expression that should be used to complete the method so that it computes the result correctly. public static double power(double base, double exponent) { if (exponent % 2 != 0) // if exponent is odd { return base * power(base, exponent - 1); } else if (exponent > 0) { double temp = ________________________ ; return temp * temp; } return base; } a) power(base, exponent / 2) b) power(base, exponent / 2) * power(base, exponent / 2) c) power(base, exponent / 2) + power(base, exponent / 2) d) power(base, exponent) / 2
a
96) Which of the following statements is correct? a) The empty string is a palindrome. b) Strings of length 0 or 1 are not palindromes. c) The string "eat" is a palindrome. d) The string "Adam" is a palindrome.
a
The partial linear search method below is designed to search an array of String objects. Select the expression that would be needed to complete the method. public static int search(String[] a, String item) { for (int i = 0; i < a.length; i++) { if ( ____________________________ ) { return i; } return -1; } }
a [i]. equals (item)
The partial binary search method below is designed to search an array of String objects sorted in ascending order. Select the expression that would be needed to complete the method. public static int search(String[] a, int low, int high, String item) if (low <= high) int mid = (low + high) / 2; int result = ____________________________; if (result == 0) return mid; else if (result < 0) return search(a, mid + 1, high, item); else return search(a, low, mid - 1, item); return -1;
a [mid].compareTo(item)
For the infix expression a + r ^ 2 - 5, the corresponding postfix expression would be _____.
a r 2 ^ + 5 ‑
Given the following infix expression, which one of the following is the corresponding postfix expression? a + r ^ 2 -5 a.a r 2 ^ + 5 - b.a r + ^ 5 - c.a r 2 5 + ^ - d.none of the above
a r 2 ^ +5 -
In a node object, the next field contains _____.
a reference to another node
Completely Balanced
a tree where subtrees are all of equal heights
What is the output of the following program when the method is called with 4? void unknown(int n) { if (n > 0) unknown(n-1); System.out.print("?"); } a) ????? b) ???? c) ??? d) none of the above
a) ?????
What is the output of the following program when the method is called with 4? void unknown(int n) { System.out.print("?"); if (n > 0) unknown(n-1); } a) ????? b) ???? c) ??? d) none of the above
a) ?????
The _____ shows a method's state during execution. a.activation record b.stack c.program counter d.program stack
activation record
In the Ch 6 linked-chain implementation of a Stack ADT, the performance of popping an entry from the stack is a) O(1) b) O(2) c) O(n) d) O(n^2)
a) O(1)
Recursive methods need a(n): a) base case b) for loop c) trace d) all of the above
a) base case
How many recursive calls will be made if the following method is called with 6 from main? void greeting(int n) { if (n > 0) { System.out.println("Hello!"); greeting(n+1); } } a) infinite b) 7 c) 6 d) 5
a) infinite
How many recursive calls will be made if the following method is called with 6 from main? void greeting(int n) { System.out.println("Hello!"); greeting(n-1); } a) infinite b) 7 c) 6 d) 5
a) infinite
The node that is easiest to access in a linked-chain is: a) the head node b) the tail node c) access time is the same for all nodes d) it cannot be determined
a) the head node
Consider the fib method from the textbook shown below: public static long fib(int n) { if (n <= 2) { return 1; } else { return fib(n - 1) + fib(n - 2); } } Computing the 7th fibonacci number, fib(7), recursively computes fib(6), fib(5), and fib(4) ___ times respectively. a. 1, 2, and 3 b. 3, 2, and 1 c. 4, 5, and 6 d. 6, 5, and 4
a. 1, 2, and 3
Consider the following code snippet: public static boolean isEven(int n) { if (n % 2 == 0) { return true; } else { return (isOdd(n)); } } public static boolean isOdd(int n) { if (n % 2 == 1) { return true; } else { return (isEven(n)); } } For any given value of n, what is the maximum number of function calls that could occur? a. 2 b. cannot be determined c. 0 d. 1
a. 2
Given the following class code: public class RecurseSample { public static void main(String[] args) { recurse(3); } public static int recurse(int n) { int total = 0; if (n == 0) { return 0; } else { total = 3 + recurse(n - 1); } System.out.println(total); return total; } } What values will be printed? a. 3, 6, and 9 b. 1, 3, and 6 c. 3, 6, 9, and 12 d. 1, 3, 6, and 9
a. 3, 6, and 9
Given the following class code: public class RecurseMore { public static void main(String[] args) { recurse(4); } public static int recurse(int n) { int total = 0; if (n == 0) { return 0; } else { total = 4 + recurse(n - 2); } System.out.println(total); return total; } } What values will be printed when this code is executed? a. 4 and 8 b. 4 c. 0, 4, and 8 d. 8
a. 4 and 8
Given the following code snippet: public static int newCalc(int n) { if (n < 0) { return -1; } else if (n < 10) { return n; } else { return (1 + newCalc(n / 10)); } } What value will be returned when this code is executed with a call to newCalc(5)? a. 5 b. 1 c. 1.5 d. 5.5
a. 5
Suppose we wrote a new version of fib called newFib. What does the call newFib(6) return? public static long newFib(int n) { if (n <= 3) { return 1; } else { return newFib(n - 1) + newFib(n - 2) + newFib(n - 3); } } a. 9 b. 3 c. 7 d. 5
a. 9
Consider the getArea method from the book shown below. public int getArea() { if (width <= 0) { return 0; } // line #1 else if (width == 1) { return 1; } // line #2 else { Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } } Assume lines #1 and #2 were replaced with this: if (width == 1) { return 1; } // replacement for lines #1 and #2 What will happen when this code is executed? a. A negative or zero width would cause problems. b. Nothing - the method would still be correct. c. We would lose our only recursive case. d. A positive width would reduce the correct area by 1.
a. A negative or zero width would cause problems.
Which of the following statements about palindromes is correct? a. All strings of length 0 or 1 are palindromes. b. The empty string is not a palindrome. c. The string "rascal" is a palindrome. d. The string "I" is not a palindrome.
a. All strings of length 0 or 1 are palindromes.
Which of the following options could be used as a terminating condition for a recursive method that finds the middle character of a String with any number of characters? I the length of the String is 1 II first and last String characters match III the String is not empty a. I b. I, II and III c. II d. I and III
a. I
Consider the fib method from the textbook shown below: public static long fib(int n) { if (n <= 2) { return 1; // line #1 } else { return fib(n - 1) + fib(n - 2); // line #2 } } Assume line #2 is changed to this: else { return 2 * fib(n - 1) + 2 * fib(n - 2); } What effect will this change have? a. This will return 10 from fib(4) b. This will return 5 from fib(4) c. This will return 8 from fib(4) d. This will cause an exception on a call fib(4)
a. This will return 10 from fib(4)
A palindrome is a word or phrase that reads the same forward or backward. Consider the methods palindrome and isPal shown below: public boolean palindrome(String string) { return isPal(string, 0, string.length() - 1); } private boolean isPal(String string, int left, int right) { if (left >= right) { return true; } else if (string.charAt(left) == string.charAt(right)) { return isPal(string, left + 1, right - 1); } else { return false; } } The method palindrome as shown here would be considered to be a ____ method. a. helper b. static c. recursive d. terminating
a. helper
Consider the following code snippet for calculating Fibonacci numbers recursively: int fib(int n) { // assumes n >= 0 if (n <= 1) { return n; } else { return (fib(n - 1) + fib(n - 2)); } } Identify the terminating condition. a. n <= 1 b. n < 1 c. fib(n - 1) d. fib(n - 1) + fib(n - 1)
a. n <= 1
Complete the following code snippet, which is intended to be a recursive method that will find the sum of all elements in an array of double values from index to the end of the array: // return the sum of all elements in arr[] public static double findSum(double arr[], int index) { if (index == 0) { return arr[index]; } else { _____________________ } } Assume that this method would be called using an existing array named myArray as follows: findSum(myArray, myArray.length - 1); a. return (arr[index] + findSum(arr, index - 1)); b. return (findSum(arr, index - 1)); c. return (arr[index] + findSum(arr, index + 1)); d. return (findSum(arr, index + 1));
a. return (arr[index] + findSum(arr, index - 1));
Complete the code for the recursive method printSum shown in this code snippet, which is intended to return the sum of digits from 1 to n: public static int printSum(int n) { if (n == 0) { return 0; } else { ______________________________ } } a. return (n + printSum(n - 1)); b. return (printSum(n - 1)); c. return (n - printSum(n - 1)); d. return (n + printSum(n + 1));
a. return (n + printSum(n - 1));
Insert the missing code in the following code fragment. This fragment is intended to recursively compute xn, where x and n are both non-negative integers: public int power(int x, int n) { if (n == 0) { ____________________ } else { return x * power(x, n - 1); } } a. return 1; b. return x; c. return x * power(x, n - 1); d. return power(x, n - 1);
a. return 1;
Complete the code for the recursive method shown below, which is intended to compute the sum of the first n integers: public int s(int n) { if (n == 1) { return 1; } else { _________________ } } a. return n + s(n - 1); b. return s(n) + n - 1; c. return n + s(n + 1); d. return n + (n - 1);
a. return n + s(n - 1);
Consider the getArea method from the textbook shown below: public int getArea() { if (width <= 0) { return 0; } // line #1 if (width == 1) { return 1; } // line #2 Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } Assume that line #3 is changed to this: Triangle smallerTriangle = new Triangle(width); This would cause infinite recursion for ____. a. triangles with width greater than or equal to 2 b. triangles with width equal to 1 c. triangles of any width d. triangles with width equal to 0
a. triangles with width greater than or equal to 2
Given the following infix expression, which one of the following is the corresponding postfix expression?(a + b) * (c -d) / (e + f) a.a b + c d -* e f + / b.a b c d e f + * -/ + c.a b + c d -e f + * / d.none of the above
ab+cd-*ef+/
The ADT priority queue organizes objects _____.
according to the priority of the objects
The _____ shows a method's state during execution.
activation record
Complete the code for the calcPower recursive method shown below, which is intended to raise the base number passed into the method to the exponent power passed into the method: public static int calcPower(int baseNum, int exponent) { int answer = 0; if (exponent == 0) { _____________________ } else { answer = baseNum * calcPower (baseNum, exponent - 1); } return answer; }
answer = 1;
An _____ is a group of variables (called elements) containing values of the same type.
array
Where does a queue add new items?
at the back
10) Consider the following recursive code snippet: public int mystery(int n, int m) { if (n == 0) { return 0; } if (n == 1) { return m; } return m + mystery(n - 1, m); } What value is returned from a call to mystery(1,5)? a) 1 b) 5 c) 6 d) 11
b
103) The method below generates all substrings of a String passed as argument. Assuming that the string contains no duplicate characters, select the statement to complete the method so that it prints all substrings correctly. public static void printSubstrings(String word) { if (word.length() > 0) { for (int j = 1; j <= word.length(); j++) // print substrings that begin { // with the first character System.out.println(word.substring(0, j)); } ___________________________________ // print substrings without } // the first character } a) printSubstrings(word.substring(0)); b) printSubstrings(word.substring(1)); c) printSubstrings(word.substring(word.length())); d) printSubstrings(word.substring(word.length() - 1));
b
108) Complete the following code snippet, which is intended to determine if a value is even or odd using mutual recursion: public static boolean isEven(int n) { if (n == 0) { return true; } else { return isOdd(Math.abs(n) - 1); } } public static boolean isOdd(int n) { if (n == 0) { _________ } else { return isEven(Math.abs(n) - 1); } } a) return true; b) return false; c) return isOdd(Math.abs(n)-1); d) return isOdd(Math.abs(n));
b
109) Backtracking _____. a) starts from the end of the program and works backward to the beginning. b) starts with a partial solution and builds it up to get closer to the goal. c) never abandons a partial solution. d) explores only one path toward a solution
b
12) Consider the recursive method myPrint : public void myPrint(int n) { if (n < 10) { System.out.print(n); } else { int m = n % 10; System.out.print(m); myPrint(n / 10); } } What is printed for the call myPrint(8)? a) 10 b) 8 c) 4 d) 21
b
13) Consider the recursive method myPrint in this code snippet: public void myPrint(int n) { if (n < 10) { System.out.print(n); } else { int m = n % 10; System.out.print(m); myPrint(n / 10); } } What is printed for the call myPrint(821) ? a) 821 b) 128 c) 12 d) 10
b
14) Consider the recursive method myPrint shown in this code snippet: public void myPrint(int n) { if (n < 10) { System.out.print(n); } else { int m = n % 10; System.out.print(m); myPrint(n / 10); } } What does this method do? a) Prints a positive int value forward, digit by digit. b) Prints a positive int value backward, digit by digit. c) Divides the int by 10 and prints out its last digit. d) Divides the int by 10 and prints out the result.
b
17) Consider the code for the recursive method myPrint shown in this code snippet: public static int myPrint(int n) { if (n == 0) { return 0; { else { return (n + myPrint(n - 1)); } } To avoid infinite recursion, which of the following lines of code should replace the current terminating case? a) if (n == -1) b) if (n <= 0) c) if (n >= 0) d) The terminating case as shown will avoid infinite recursion.
b
20) Consider the recursive method shown below: public static int strangeCalc(int bottom, int top) { if (bottom > top) { return -1; } else if (bottom == top) { return 1; } else { return bottom * strangeCalc(bottom + 1, top); } } What value will be returned with a call to strangeCalc(2,3)? a) 1 b) 2 c) 6 d) 24
b
27) Consider the getArea method from the textbook shown below: public int getArea() { if (width <= 0) { return 0; } // line #1 Triangle smallerTriangle = new Triangle(width - 1); // line #2 int smallerArea = smallerTriangle.getArea(); // line #3 return smallerArea + width; // line #4 } If line#1 was removed, what would be the result? a) The recursive method would cause an exception for values below 0. b) The recursive method would construct triangles whose width was negative. c) The recursive method would terminate when the width reached 0. d) The recursive method would correctly calculate the area of the original triangle.
b
36) Consider the problem of arranging matchsticks so as to form a row of rectangles, as shown below. _ _ _ _ _ _ |_ _|_ _|_ _| Complete the recursive method below, which is designed to return the number of matchsticks needed to form n rectangles. public static int matchsticks(int rectangles) { if (rectangles == 1) // 1 square can be formed with 6 matchsticks { return 6; } else { return ___________________________ } } a) 6 + matchsticks(rectangles - 1); b) 5 + matchsticks(rectangles - 1); c) 6 * rectangles; d) matchsticks(rectangles + 6);
b
A unique permutation is one that is different from any other generated permutation. How many unique permutations does the string "aaa" have? a. 0 b. 1 c. 2 d. 3
b. 1
39) Consider the method below, which prints the digits of an arbitrary integer in reverse order, one digit per line. The method should print the last digit first. Then, it should recursively print the integer obtained by removing the last digit. Select the statements that should be used to complete the method. public static void printReverse(int value) { if (value > 0) { _____________________ // print last digit _____________________ // recursive call to print value without last digit } } Maha Otaibi 67 a) System.out.println(value / 10); printReverse(value / 10); b) System.out.println(value % 10); printReverse(value / 10); c) System.out.println(value / 10); printReverse(value % 10); d) System.out.println(value % 10); printReverse(value % 10);
b
48) Complete the code for the calcPower recursive method shown below, which is intended to raise the base number passed into the method to the exponent power passed into the method: public static int calcPower(int baseNum, int exponent) { int answer = 0; if (exponent == 0) { _____________________ } else { answer = baseNum * calcPower (baseNum, exponent - 1); } return answer; } a) answer = 0; b) answer = 1; c) answer = -1; d) answer = calcPower(1);
b
49) Complete the code for the calcPower recursive method shown below, which is intended to raise the base number passed into the method to the exponent power passed into the method: public static int calcPower(int baseNum, int exponent) { int answer = 0; if (exponent == 0) { answer = 1; } else { _______________________________________ } return answer; } a) answer = baseNum * calcPower (baseNum -1, exponent); b) answer = baseNum * calcPower (baseNum, exponent - 1); c) answer = baseNum * calcPower (baseNum, exponent); d) answer = baseNum * calcPower (baseNum -1, exponent - 1);
b
51) Given the following class code: public class RecurseSample { public static void main(String[] args) { System.out.println(recurse(3)); } public static int recurse(int n) { int total = 0; if (n == 0) { return 0; } else { total = 3 + recurse(n - 1); } return total; } } What values will be printed when this code is executed? a) 6 b) 9 c) 3, 6, and 9 d) 1, 3, 6, and 9
b
52) Given the following class code: public class RecurseMore { public static void main(String[] args) { recurse(4); } public static int recurse(int n) { int total = 0; if (n == 0) { return 0; } else { total = 4 + recurse(n - 2); } System.out.println(total); return total; } } What values will be printed when this code is executed? a) 0, 4, and 8 b) 4 and 8 c) 4 d) 8
b
66) A palindrome is a word or phrase that reads the same forward or backward. Consider the following code snippet: public boolean palindrome(String string) { return isPal(string, 0, string.length() - 1); } private boolean isPal(String string, int left, int right) { if (left >= right) { return true; } else if (string.charAt(left) == string.charAt(right)) { return isPal(string, left + 1, right - 1); } else { return false; } } What is the purpose of the palindrome method? a) Return the palindrome to the calling method. b) Provide the string, along with its first and last indexes to the recursive isPal method. c) Send the recursive isPal method its terminating condition. d) Recursively call itself.
b
76) Why does the best recursive method usually run slightly slower than its iterative counterpart? a) Testing the terminating condition takes longer. b) Each recursive method call takes processor time. c) Multiple recursive cases must be considered. d) Checking multiple terminating conditions take more processor time.
b
78) Consider the fib method from the textbook shown below. public static long fib(int n) { if (n <= 2) { return 1; } else { return fib(n - 1) + fib(n - 2); } } Calling fib(3) will trigger ___ recursive call(s) and execute the terminating condition ___ time(s), respectively. a) 1, 1 b) 2, 2 c) 1, 2 d) 2, 1
b
8) Consider the following code snippet for calculating Fibonacci numbers recursively: int fib(int n) { // assumes n >= 0 if (n <= 1) { return n; } else { return (fib(n - 1) + fib(n - 2)); } } Identify the terminating condition. a) n < 1 b) n <= 1 c) fib(n - 1) d) fib(n - 1) + fib(n - 1)
b
81) Consider the fib method from the textbook shown below: public static long fib(int n) { if (n <= 2) { return 1; // line #1 } else { return fib(n - 1) + fib(n - 2); // line #2 } } Assume line #1 is changed to this: if (n <= 2) { return n; } What effect will this change have? a) This will return 21 from fib(6) b) This will return 13 from fib(6) c) This will return 8 from fib(6) d) This will return 6 from fib(6)
b
84) Consider the recursive version of the fib method from the textbook shown below: public static long fib(int n) { if (n <= 2) { return 1; } else { return fib(n - 1) + fib(n - 2); } } How many total recursive calls (not counting the original call) to fib will be made from the original call of fib(7)? a) 12 b) 24 c) 30 d) 32
b
98) A unique permutation is one that is different from any other generated permutation. How many unique permutations does the string "bee" have? a) 2 b) 3 c) 4 d) 5
b
99) A unique permutation is one that is different from any other generated permutation. How many unique permutations does the string "aaa" have? a) 0 b) 1 c) 2 d) 3
b
What is the output of the following program when the method is called with 4? void unknown(int n) { if (n > 0) { System.out.print("?"); unknown(n-1); } } a) ????? b) ???? c) ??? d) none of the above
b) ????
The efficiency for recursively traversing a chain of linked nodes is: a) O(1) b) O(n) c) O(n2) d) It cannot be proven
b) O(n)
In the Ch 6 array-based implementation of a Stack ADT, the entry peek returns may be found at: a) the first location in the array b) the last occupied location in the array c) the last location in the array d) none of the above
b) the last occupied location in the array
How many recursive calls to the fib method shown below would be made from an original call to fib(4)? (Do not count the original call) public int fib(int n) { // assumes n >= 0 if (n <= 1) { return n } else { return (fib(n - 1) + fib(n - 2)); } } a. 2 b. 8 c. 4 d. 1
b. 8
If a recursive method does not simplify the computation within the method and the base case is not called, what will be the result? a. The recursion calculation will occur correctly regardless. b. Infinite recursion will occur. c. This cannot be determined. d. The terminating condition will be executed and recursion will end.
b. Infinite recursion will occur.
Consider the recursive method myPrint shown in this code snippet: public void myPrint(int n) { if (n < 10) { System.out.print(n); } else { int m = n % 10; System.out.print(m); myPrint(n / 10); } } What does this method do? a. Divides the int by 10 and prints out the result. b. Prints a positive int value backward, digit by digit. c. Divides the int by 10 and prints out its last digit. d. Prints a positive int value forward, digit by digit.
b. Prints a positive int value backward, digit by digit.
Complete the code for the calcPower recursive method shown below, which is intended to raise the base number passed into the method to the exponent power passed into the method: public static int calcPower(int baseNum, int exponent) { int answer = 0; ________________________ { answer = 1; } else { answer = baseNum * calcPower (baseNum, exponent - 1); } return answer; } a. if (exponent == -1) b. if (exponent == 0) c. if (exponent != 1) d. if (exponent == 1)
b. if (exponent == 0)
Consider the getArea method from the textbook shown below: public int getArea() { if (width <= 0) { return 0; } // line #1 if (width == 1) { return 1; } // line #2 Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } Which line has the recursive case? a. line #3 b. line #4 c. line #2 d. line #1
b. line #4
Consider the mutually recursive methods below. Select the method call that could be used to generate the output sequence: A5 B4 A3 B2 A1 public static void methodA(int value) { if (value > 0) { System.out.print(" A" + value); methodB(value - 1); } } public static void methodB(int value) { if (value > 0) { System.out.print(" B" + value); methodA(value - 1); } } a. methodA(4); b. methodA(5); c. methodB(5); d. methodB(4);
b. methodA(5);
The method below generates all substrings of a String passed as argument. Assuming that the string contains no duplicate characters, select the statement to complete the method so that it prints all substrings correctly. public static void printSubstrings(String word) { if (word.length() > 0) { for (int j = 1; j <= word.length(); j++) // print substrings that begin with the first character { System.out.println(word.substring(0, j)); } _________________________________ // print substrings without the first character } } a. printSubstrings(word.substring(word.length() - 1)); b. printSubstrings(word.substring(1)); c. printSubstrings(word.substring(0)); d. printSubstrings(word.substring(word.length()));
b. printSubstrings(word.substring(1));
Complete the following code snippet, which is intended to be a recursive method that will find the sum of all elements in an array of double values from index to the end of the array: // return the sum of all elements in arr[] public static double findSum(double arr[], int index) { if (index == 0) { _____________________ } else { return (arr[index] + findSum(arr, index - 1)); } } Assume that this method would be called using an existing array named myArray as follows: findSum(myArray,myArray.length - 1); a. return arr[index + 1]; b. return arr[index]; c. return arr[index - 1]; d. return arr[1];
b. return arr[index];
Complete the following code snippet, which is intended to be a recursive method that will find the smallest value in an array of double values from index to the end of the array: public static double minVal(double[] elements, int index) { if (index == elements.length - 1) { __________________ } double val = minVal(elements, index + 1); if (elements[index] < val) { return elements[index]; } else { return val; } } a. return 0; b. return elements[index]; c. return 1; d. return elements[0];
b. return elements[index];
Complete the following code snippet, which is intended to determine if a value is even or odd using mutual recursion: public static boolean isEven(int n) { if (n == 0) { return true; } else { return isOdd(Math.abs(n) - 1); } } public static boolean isOdd(int n) { if (n == 0) { _________ } else { return isEven(Math.abs(n) - 1); } } a. return isOdd(Math.abs(n)-1); b. return false; c. return isOdd(Math.abs(n)); d. return true;
b. return false;
Complete the following code snippet, which is intended to be a recursive method that reverses a String value: public static String reverseIt(String s) { if (s.length() <= 1) { return s; } else { ________________________ } } a. return reverseIt(s.substring(0)) + s.charAt(1); b. return reverseIt(s.substring(1)) + s.charAt(0); c. return reverseIt(s.substring(1)) + s.charAt(1); d. return reverseIt(s.substring(0)) + s.charAt(0);
b. return reverseIt(s.substring(1)) + s.charAt(0);
Assume that recursive method search returns true if argument value is one of the elements in the section of the array limited by the firstIndex and lastIndex arguments. What statement can be used in main to determine if the value 7 is one of the elements in array values? public static boolean search(int value, int[] array, int firstIndex, int lastIndex) { if (firstIndex <= lastIndex) { if (array[firstIndex] == value) { return true; } else { return search(value, array, firstIndex + 1, lastIndex); } } return false; } public static void main(String[] args) { int [] values = { 4, 7, 1, 0, 2, 7 }; if (_________________________________ ) { System.out.println("7 is in the array"); } } a. search(7, values, 0, values.length) b. search(7, values, 0, values.length - 1) c. search(7, values, 1, values.length) d. search(7, values, 1, values.length - 1)
b. search(7, values, 0, values.length - 1)
In recursion, the non-recursive case is analogous to a loop ____. a. call b. termination c. condition d. iteration
b. termination
An expression that has correctly paired delimiters is called a(n) a.balanced expression b.Reverse Polish expression c.infix expression d.algebraic expression
balanced expression
Assume that bands is an ArrayList of String objects which contains a number of elements in ascending order. Select a statement to complete the code segment below, which invokes the Java library binarySearch method to search for the string "Beatles". If the list does not already contain the string, it should be inserted in an appropriate location so that the list remains sorted. int index = Collections.binarySearch(bands, "Beatles"); if (index < 0) __________________________
bands.add(-1-index, "Beatles");
A search technique where, in each step, you split the size of the search in half is called a____ search.
binary
In a linked chain implementation of a queue, when the queue is empty
both & b
If we use a chain of linked nodes with only a head reference to implement a queue which statement is true?
both a & b
How can we tell if a two-part circular linked chain queue is empty?
both the queueNode and freeNode reference the same Node
1) What is required to make a recursive method successful? I special cases that handle the simplest computations directly II a recursive call to simplify the computation III a mutual recursion a) I b) II c) I and II d) I, II, and III
c
107) Consider the following code snippet: public static boolean isEven(int n) { if (n % 2 == 0) { return true; } else { return (isOdd(n)); } } public static boolean isOdd(int n) { if (n % 2 == 1) { return true; } else { return (isEven(n)); } } For any given value of n, what is the maximum number of function calls that could occur? a) 0 b) 1 c) 2 d) cannot be determined
c
11) Consider the following recursive code snippet: public int mystery(int n, int m) { if (n == 0) { return 0; } if (n == 1) { return m; } return m + mystery(n - 1, m); } What value is returned from a call to mystery(3,6) ? a) 3 b) 6 c) 18 d) 729
c
110) ____ is a problem-solving technique that examines partial solutions, abandons unsuitable ones, and returns to consider other candidate solutions. a) Debugging b) Traceback c) Backtracking d) Recursion
c
15) Complete the code for the recursive method printSum shown in this code snippet, which is intended to return the sum of digits from 1 to n: public static int printSum(int n) { if (n == 0) { return 0; } else { ______________________________ } } a) return (printSum(n - 1)); b) return (n + printSum(n + 1)); c) return (n + printSum(n - 1)); d) return (n - printSum(n - 1));
c
19) Consider the recursive method shown below: public static int strangeCalc(int bottom, int top) { if (bottom > top) { return -1; } else if (bottom == top) { return 1; } else { return bottom * strangeCalc(bottom + 1, top); } } What value will be returned with a call to strangeCalc(4,7)? a) 1 b) -1 c) 120 d) 840
c
22) If recursion does not have a special terminating case, what error will occur? a) Index out of range b) Illegal argument c) Stack overflow d) Out of memory
c
24) Consider the following recursive code snippet: public int mystery(int n, int m) { if (n == 0) { return 0; } if (n == 1) { return m; } return m + mystery(n - 1, m); } What parameter values for n would cause an infinite recursion problem in the following method? a) n == 0 b) n == 1 c) all n with n < 0 d) all n with n >= 0
c
3) Consider the getArea method from the textbook shown below. public int getArea() { if (width <= 0) { return 0; } // line #1 else if (width == 1) { return 1; } // line #2 else { Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } } Where is/are the terminating condition(s)? a) line #1 b) line #2 c) lines #1 and #2 d) line #4
c
30) Consider the getArea method from the textbook shown below: public int getArea() { if (width <= 0) { return 0; } // line #1 if (width == 1) { return 1; } // line #2 Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } Assume that line #3 is changed to this: Triangle smallerTriangle = new Triangle(width); This would cause infinite recursion for ____. a) triangles with width equal to 0 b) triangles with width equal to 1 c) triangles with width greater than or equal to 2 d) triangles of any width
c
38) Consider the method below, which displays the characters from a String in reverse order. Each character appears on a separate line. Select the statement that should be used to complete the method, so that it performs a recursive method call correctly. public static void printReverse(String word) { if (word.length() > 0) { ___________________________ System.out.println(word.charAt(0)); } } a) printReverse(word); b) printReverse(new String(word.charAt(1))); c) printReverse(word.substring(1)); d) printReverse(word.length() - 1);
c
4) Consider the getArea method from the textbook shown below: public int getArea() { if (width <= 0) { return 0; } // line #1 else if (width == 1) { return 1; } // line #2 else { Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } } Assume the code in line #3 is changed to: Triangle smallerTriangle = new Triangle(width); This change would cause infinite recursion for which triangles? a) Those with width equal to 0. b) Those with width equal to 1. c) Those with width greater than or equal to 2. d) Triangles of any width.
c
43) Complete the code for the myFactorial recursive method shown below, which is intended to compute the factorial of the value passed to the method: public int myFactorial(int anInteger) { if (anInteger == 1) { return 1; } else { ______________________ } } a) return(anInteger * (myFactorial(anInteger))); b) return ((anInteger - 1) * (myFactorial(anInteger))); c) return(anInteger * (myFactorial(anInteger - 1))); d) return((anInteger - 1)*(myFactorial(anInteger - 1)));
c
45) Complete the code for the myFactorial recursive method shown below, which is intended to compute the factorial of the value passed to the method: public int myFactorial(int anInteger) { if (anInteger == 1) { ______________________ } else { return (anInteger * myFactorial(anInteger - 1)); } } a) return 0; b) return -anInteger; c) return 1; d) return myFactorial(anInteger);
c
46) Complete the code for the recursive method shown below, which is intended to compute the sum of the first n integers: public int s(int n) { if (n == 1) { return 1; } else { _________________ } } a) return n + (n - 1); b) return s(n) + n - 1; c) return n + s(n - 1); d) return n + s(n + 1);
c
50) Given the following class code: public class RecurseSample { public static void main(String[] args) { recurse(3); } public static int recurse(int n) { int total = 0; if (n == 0) { return 0;} else { total = 3 + recurse(n - 1); } System.out.println(total); return total; } } What values will be printed? a) 1, 3, and 6 b) 1, 3, 6, and 9 c) 3, 6, and 9 d) 3, 6, 9, and 12
c
53) Given the following code snippet: public static int newCalc(int n) { if (n < 0) { return -1; } else if (n < 10) { return n; } else { return (n % 10) + newCalc(n / 10); } } What value will be returned when this code is executed with a call to newCalc(15)? a) 2 b) 2.5 c) 6 d) 6.5
c
54) Given the following code snippet: public static int newCalc(int n) { if (n < 0) { return -1; } else if (n < 10) { return n; } else { return (n % 10) + newCalc(n / 10); } } What value will be returned when this code is executed with a call to newCalc(5)? a) 2 b) 2.5 c) 5 d) 5.5
c
55) Given the following code snippet: public static int newCalc(int n) { if (n < 0) { return -1; } else if (n < 10) { return n; } else { return (1 + newCalc(n / 10)); } } What value will be returned when this code is executed with a call to newCalc(5)? a) 1 b) 1.5 c) 5 d) 5.5
c
58) Complete the following code snippet, which is intended to be a recursive method that will find the smallest value in an array of double values from index to the end of the array: public static double minVal(double[] elements, int index) { if (index == elements.length - 1) { return elements[index]; } double val = __________________; if (elements[index] < val) { return elements[index]; } else { return val; } } a) minVal(elements, index - 1) b) minVal(index - 1) c) minVal(elements, index + 1) d) minVal(index + 1)
c
65) A palindrome is a word or phrase that reads the same forward or backward. Consider the methods palindrome and isPal shown below: public boolean palindrome(String string) { return isPal(string, 0, string.length() - 1); } private boolean isPal(String string, int left, int right) { if (left >= right) { return true; } else if (string.charAt(left) == string.charAt(right)) { return isPal(string, left + 1, right - 1); } else { return false; } } The method palindrome as shown here would be considered to be a ____ method. a) recursive b) terminating c) helper d) static
c
74) Assume that recursive method search returns true if argument value is one of the elements in the section of the array limited by the firstIndex and lastIndex arguments. What statement can be used in main to determine if the value 7 is one of the elements in array values? public static boolean search(int value, int[] array, int firstIndex, int lastIndex) { if (firstIndex <= lastIndex) { if (array[firstIndex] == value) { return true; } else { return search(value, array, firstIndex + 1, lastIndex); } } return false; } public static void main(String[] args) { int [] values = { 4, 7, 1, 0, 2, 7 }; if ( _________________________________ ) { System.out.println("7 is in the array"); } } a) search(7, values, 0, values.length) b) search(7, values, 1, values.length) c) search(7, values, 0, values.length - 1) d) search(7, values, 1, values.length - 1)
c
75) Consider the problem of displaying a pattern of asterisks which form a triangle of height h, as shown below for h = 4: * ** *** **** *** ** * The problem can be solved with the recursive helper method shape below. The method takes two parameters: low and high. It first prints a row of asterisks corresponding to parameter low. If high is higher than low, it recursively generates a shape in which low is incremented by one, and then prints another row of low asterisks. Select a statement to complete method triangle, so that the helper method shape is invoked with the correct arguments in order to display a triangle with parameter height. public static void shape(int low, int high) { if (high >= low) { asterisksRow(low); if (high > low) { shape(low + 1, high); asterisksRow(low); } } } public static void asterisksRow(int n) // Method to display a row of n stars { for (int j = 1; j < n; ++j) { System.out.print("*"); } System.out.println("*"); } public static void triangle(int height) { if (height > 1) { _______________________ }} a) shape(0, height); b) shape(0, height - 1); c) shape(1, height); d) shape(0, height - 1);
c
83) Consider the recursive version of the fib method from the textbook shown below: public static long fib(int n) { if (n <= 2) { return 1; } else { return fib(n - 1) + fib(n - 2); } } How many total recursive calls (not counting the original call) to fib will be made from the original call of fib(6)? a) 6 b) 12 c) 14 d) 20
c
87) Consider the iterative version of the fib method from the textbook shown below: public static long fib(int n) { if (n <= 2) { return 1; } long fold = 1; long fold2 = 1; long fnew = 1; for (int i = 3; i <= n; i++) { fnew = fold + fold2; fold2 = fold; fold = fnew; } return fnew; } How many iterations of the for loop will there be for the call fib(6)? a) 6 b) 5 c) 4 d) 3
c
9) Consider the following recursive code snippet: public static int mystery(int n, int m) { if (n <= 0) { return 0; } if (n == 1) { return m; } return m + mystery(n - 1, m); } Identify the terminating condition(s) of method mystery? a) n <= 0 b) n == 1 c) n <= 0 or n == 1 d) n > 0
c
90) Which statement(s) about recursion are true? I Recursion is faster than iteration II Recursion is often easier to understand than iteration III Recursive design has an economy of thought a) I b) II c) II and III d) I and III
c
92) In recursion, the non-recursive case is analogous to a loop ____. a) call b) iteration c) termination d) condition
c
93) In recursion, the terminating condition is analogous to a loop _________. a) call b) iteration c) termination condition d) initialization condition
c
97) The string "eat" has ____ permutations. a) 2 b) 4 c) 6 d) 8
c
In the Ch 6 an array-based implementation of a Stack ADT, what value for the topindex of the stack indicates that it is empty? a) 0 b) 1 c) -1 d) null
c) -1
How many recursive calls will be made if the following method is called with 6 from main? void greeting(int n) { if (n > 0) { System.out.println("Hello!"); greeting(n-1); } } a) infinite b) 7 c) 6 d) 5
c) 6
When too many recursive calls are made creating more activation records than the allocated program memory can handle, what kind of error occurs? a) recursive overflow b) infinite recursion c) stack overflow d) activation record overflow
c) stack overflow
_____ is the hiding of implementation details behind an interface.
encapsulation
Consider the fib method from the textbook shown below. public static long fib(int n) { if (n <= 2) { return 1; } else { return fib(n - 1) + fib(n - 2); } } Calling fib(3) will trigger ___ recursive call(s) and execute the terminating condition ___ time(s), respectively. a. 1, 2 b. 1, 1 c. 2, 2 d. 2, 1
c. 2, 2
Consider the recursive version of the fib method from the textbook shown below: public static long fib(int n) { if (n <= 2) { return 1; } else { return fib(n - 1) + fib(n - 2); } } How many recursive calls to fib(2) will be made from the original call of fib(6)? a. 3 b. 4 c. 5 d. 2
c. 5
Given the following class code: public class RecurseSample { public static void main(String[] args) { System.out.println(recurse(3)); } public static int recurse(int n) { int total = 0; if (n == 0) { return 0; } else { total = 3 + recurse(n - 1); } return total; } } What values will be printed when this code is executed? a. 6 b. 1, 3, 6, and 9 c. 9 d. 3, 6, and 9
c. 9
____ is a problem-solving technique that examines partial solutions, abandons unsuitable ones, and returns to consider other candidate solutions. a. Traceback b. Recursion c. Backtracking d. Debugging
c. Backtracking
Which statement(s) about recursion are true? I Recursion is faster than iteration II Recursion is often easier to understand than iteration III Recursive design has an economy of thought a. I and III b. I c. II and III d. II
c. II and III
Would switching the special case order affect the return value of the following method? public int mystery(int n, int m) { if (n == 0) // special case #1 { return 0; } if (n == 1) // special case #2 { return m; } return m + mystery(n - 1, m); } a. An exception will be thrown. b. Yes c. No d. It is impossible to tell.
c. No
A palindrome is a word or phrase that reads the same forward or backward. Consider the following code snippet: public boolean palindrome(String string) { return isPal(string, 0, string.length() - 1); } private boolean isPal(String string, int left, int right) { if (left >= right) { return true; } else if (string.charAt(left) == string.charAt(right)) { return isPal(string, left + 1, right - 1); } else { return false; } } What is the purpose of the palindrome method? a. Return the palindrome to the calling method. b. Send the recursive isPal method its terminating condition. c. Provide the string, along with its first and last indexes to the recursive isPal method. d. Recursively call itself.
c. Provide the string, along with its first and last indexes to the recursive isPal method.
Consider the method below, which prints the digits of an arbitrary integer in reverse order, one digit per line. The method should print the last digit first. Then, it should recursively print the integer obtained by removing the last digit. Select the statements that should be used to complete the method. public static void printReverse(int value) { if (value > 0) { _____________________ // print last digit _____________________ // recursive call to print value without last digit } } a. System.out.println(value % 10); printReverse(value % 10); b. System.out.println(value / 10); printReverse(value % 10); c. System.out.println(value % 10); printReverse(value / 10); d. System.out.println(value / 10); printReverse(value / 10);
c. System.out.println(value % 10); printReverse(value / 10);
Consider the fib method from the textbook shown below: public static long fib(int n) { if (n <= 2) { return 1; // line #1 } else { return fib(n - 1) + fib(n - 2); // line #2 } } Assume line #1 is changed to this: if (n <= 2) { return n; } What effect will this change have? a. This will return 6 from fib(6) b. This will return 21 from fib(6) c. This will return 13 from fib(6) d. This will return 8 from fib(6)
c. This will return 13 from fib(6)
Consider the getArea method from the textbook shown below: public int getArea() { if (width <= 0) { return 0; } // line #1 else if (width == 1) { return 1; } // line #2 else { Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } } Assume the code in line #3 is changed to: Triangle smallerTriangle = new Triangle(width); This change would cause infinite recursion for which triangles? a. Triangles of any width. b. Those with width equal to 1. c. Those with width greater than or equal to 2. d. Those with width equal to 0.
c. Those with width greater than or equal to 2.
Consider the following recursive code snippet: public int mystery(int n, int m) { if (n == 0) { return 0; } if (n == 1) { return m; } return m + mystery(n - 1, m); } What parameter values for n would cause an infinite recursion problem in the following method? a. all n with n >= 0 b. n == 0 c. all n with n < 0 d. n == 1
c. all n with n < 0
Complete the code for the calcPower recursive method shown below, which is intended to raise the base number passed into the method to the exponent power passed into the method: public static int calcPower(int baseNum, int exponent) { int answer = 0; if (exponent == 0) { answer = 1; } else { _______________________________________ } return answer; } a. answer = baseNum * calcPower (baseNum, exponent); b. answer = baseNum * calcPower (baseNum -1, exponent - 1); c. answer = baseNum * calcPower (baseNum, exponent - 1); d. answer = baseNum * calcPower (baseNum -1, exponent);
c. answer = baseNum * calcPower (baseNum, exponent - 1);
_____ is a disadvantage of using an array to implement the ADT bag.
increasing the size of the array requires time to copy its entries
Consider the following code snippet for recursive addition: int add(int i, int j) { // assumes i >= 0 if (i == 0) { return j; } else { return add(i - 1, j + 1); } } Identify the terminating condition in this recursive method. a. return add(i - 1, j + 1) b. return j c. if (i == 0) d. there is no terminating condition
c. if (i == 0)
Question 1 1 pts Complete the code for the myFactorial recursive method shown below, which is intended to compute the factorial of the value passed to the method: public int myFactorial(int anInteger) { _____________________________ { return 1; } else { return(anInteger * myFactorial(anInteger - 1)); } } a. if (anInteger * (anInteger - 1) == 1) b. if (myFactorial(anInteger) == 1) c. if (anInteger == 1) d. if ((anInteger - 1) == 1)
c. if(anInteger == 1)
Consider the getArea method from the textbook shown below. public int getArea() { if (width <= 0) { return 0; } // line #1 else if (width == 1) { return 1; } // line #2 else { Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } } Where is/are the recursive call(s)? a. lines #1 and #2 b. line #2 c. line #4 d. line #1
c. line #4
The method below implements the exponentiation operation recursively by taking advantage of the fact that, if the exponent n is even, then xn = (xn/2)2. Select the expression that should be used to complete the method so that it computes the result correctly. public static double power(double base, double exponent) { if (exponent % 2 != 0) // if exponent is odd { return base * power(base, exponent - 1); } else if (exponent > 0) { double temp = ________________________ ; return temp * temp; } return base; } a. power(base, exponent / 2) * power(base, exponent / 2) b. power(base, exponent / 2) + power(base, exponent / 2) c. power(base, exponent) / 2 d. power(base, exponent / 2)
c. power(base, exponent) / 2
Consider the helper method reversePrint, which uses recursion to display in reverse the elements in a section of an array limited by the firstIndex and lastIndex arguments. What statement should be used to complete the recursive method? public static void reversePrint(int[] array, int firstIndex, int lastIndex) { if (firstIndex < lastIndex) { ________________________________________ } System.out.println(array[firstIndex]); } public static void main(String[] args) { int [] numbers = { 4, 7, 1, 0, 2, 7 }; reversePrint(numbers, 0, numbers.length - 1); } a. reversePrint(array, firstIndex + 1, lastIndex - 1); b. reversePrint(array, firstIndex, lastIndex + 1); c. reversePrint(array, firstIndex + 1, lastIndex); d. reversePrint(array, firstIndex, lastIndex - 1);
c. reversePrint(array, firstIndex + 1, lastIndex);
In the ArrayBag implementation, if the client does not specify the size of the bag, the numberOfEntries field will be set to the _____ value in the constructor.
capacity
An array whose index of the first location follows the index of its last one is called _____.
circular
In a ______ the last node references the first node.
circular linked chain
The operation to remove all entries from a stack is called a(n) a.clear b.remove c.removeAll d.empty
clear
100) Which of the following statements about palindromes is correct? a) The empty string is not a palindrome. b) The string "I" is not a palindrome. c) The string "rascal" is a palindrome. d) All strings of length 0 or 1 are palindromes.
d
102) Which of the following statements about recursion is correct? a) It is not necessary to have a special terminating case in all recursions. b) It is not necessary to simplify the argument in the recursive call. c) A recursive solution will always run faster than an equivalent iterative solution. d) In many cases, a recursive solution will be easier to understand and to implement than an iterative solution.
d
106) Recursion does NOT take place if any of the following happen: I method A calls method B, which calls method C, which calls method B II method A calls method B, which calls method A III method A calls method B, B returns, and A calls B again a) I b) I and II c) II d) III
d
16) Consider the code for the recursive method mysteryPrint shown in this code snippet: public static int mysteryPrint(int n) { if (n == 0) { return 0; } else { return (n + mysteryPrint(n-1)); } } What will be printed with a call to mysteryPrint(-4)? a) 0 b) -10 c) -22 d) Nothing - a StackoverflowError exception will occur
d
18) Consider the getArea method from the textbook shown below: public int getArea() { if (width <= 0) { return 0; } // line #1 if (width == 1) { return 1; } // line #2 Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } Which line has the recursive case? a) line #1 b) line #2 c) line #3 d) line #4
d
2) Consider the getArea method from the textbook shown below. public int getArea() { if (width <= 0) { return 0; } // line #1 else if (width == 1) { return 1; } // line #2 else { Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } } Where is/are the recursive call(s)? a) line #1 b) line #2 c) lines #1 and #2 d) line #4
d
23) A recursive method without a special terminating case would _________ a) end immediately. b) not be recursive. c) be more efficient. d) never terminate.
d
25) ____ recursion can occur when a recursive algorithm does not contain a special case to handle the simplest computations directly. a) Mutual b) Non-mutual c) Terminating condition d) Infinite
d
26) If a recursive method does not simplify the computation within the method and the base case is not called, what will be the result? a) The terminating condition will be executed and recursion will end. b) The recursion calculation will occur correctly regardless. c) This cannot be determined. d) Infinite recursion will occur.
d
31) Consider the getArea method from the textbook shown below: public int getArea() { if (width <= 0) { return 0; } // line #1 if (width == 1) { return 1; } // line #2 Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } Assume line #3 is changed to this: Triangle smallerTriangle = new Triangle(width + 1) When calling the getArea method on a Triangle object with width = 4, what result will be produced? a) area for all triangles will be computed to be too high b) area for all triangles will be computed to be too low c) area will only be incorrect for a triangle objects with width = 1 d) infinite recursion will occur for triangle objects with width >= 2
d
33) How many recursive calls to the fib method shown below would be made from an original call to fib(4)? (Do not count the original call) public int fib(int n) { // assumes n >= 0 if (n <= 1) { return n } else { return (fib(n - 1) + fib(n - 2)); } } a) 1 b) 2 c) 4 d) 8
d
41) Consider the method powerOfTwo shown below: public boolean powerOfTwo(int n) { if (n == 1) // line #1 { return true; } else if (n % 2 == 1) // line #2 { return false; } else { return powerOfTwo(n / 2); // line #3 } } How many recursive calls are made from the original call powerOfTwo(63) (not including the original call)? a) 6 b) 4 c) 1 d) 0
d
57) Given the following class code: public class RecurseMore { private static int total; public static void main(String[] args) { System.out.println(recurse(4)); } public static int recurse(int n) { int total = 0; if (n == 0) { return 0; } else { total = 4 + recurse(n - 2); } return total; } } What values will be printed when this code is executed? a) 0, 4, and 8 b) 4 and 8 c) 4 d) 8
d
63) Complete the following code snippet, which is intended to be a recursive method that reverses a String value: public static String reverseIt(String s) { if (s.length() <= 1) { return s; } else { ________________________ } } a) return reverseIt(s.substring(0)) + s.charAt(1); b) return reverseIt(s.substring(0)) + s.charAt(0); c) return reverseIt(s.substring(1)) + s.charAt(1); d) return reverseIt(s.substring(1)) + s.charAt(0);
d
64) Consider the code for the recursive method printSum shown in this code snippet, which is intended to return the sum of digits from 1 to n: public static int printSum(int n) { if (n <= 0) // line #1 { return 0; // line # } else { return (n + printSum(n)); //line #3 } } Which of the following statements is correct? a) line #1 is incorrect, and should be changed to if (n <= 1) b) line #3 is incorrect, and should be changed to return (printSum (n - 1)); c) line #3 is incorrect, and should be changed to return (n + printSum (n + 1)); d) line #3 is incorrect, and should be changed to return (n + printSum (n - 1));
d
67) A palindrome is a word or phrase spelled which reads the same forward or backward. Consider the following code snippet: public boolean palindrome(String string) { return isPal(string, 0, string.length() - 1); } private boolean isPal(String string, int left, int right) { if (left >= right) { return true; } else if (string.charAt(left) == string.charAt(right)) { return isPal(string, left + 1, right - 1); } else { return false; } } What does the method palindrome return? a) true b) false c) a palindrome not found exception d) the Boolean value returned from the isPal method
d
72) Consider the recursive square method shown below that takes a non-negative int argument. public int square(int n) { return square(n, n); } public int square(int c, int n) { if (c == 1) { return n; } else { return n + square(c - 1, n); } } Assume that the last return statement is changed to this: return n * square(c - 1, n); What would a call to square(4) return? a) 4 b) 16 c) 64 d) 256
d
73) Consider the helper method reversePrint, which uses recursion to display in reverse the elements in a section of an array limited by the firstIndex and lastIndex arguments. What statement should be used to complete the recursive method? public static void reversePrint(int[] array, int firstIndex, int lastIndex) { if (firstIndex < lastIndex) { ________________________________________ } System.out.println(array[firstIndex]); } public static void main(String[] args) { int [] numbers = { 4, 7, 1, 0, 2, 7 }; reversePrint(numbers, 0, numbers.length - 1); } a) reversePrint(array, firstIndex, lastIndex + 1); b) reversePrint(array, firstIndex, lastIndex - 1); c) reversePrint(array, firstIndex + 1, lastIndex - 1); d) reversePrint(array, firstIndex + 1, lastIndex);
d
82) Consider the recursive version of the fib method from the textbook shown below: public static long fib(int n) { if (n <= 2) { return 1; } else { return fib(n - 1) + fib(n - 2); } } How many recursive calls to fib(2) will be made from the original call of fib(6)? a) 2 b) 3 c) 4 d) 5
d
85) Consider the recursive version of the fib method from the textbook shown below: public static long fib(int n) { if (n <= 2) { return 1; } else { return fib(n - 1) + fib(n - 2); }} How many more recursive calls to fib will be made from the original call of fib(7) than from the original call of fib(6) (not counting the original calls)? a) 1 b) 2 c) 5 d) 10
d
88) Suppose we wrote a new version of fib called newFib. What does the call newFib(6) return? public static long newFib(int n) { if (n <= 3) { return 1; } else { return newFib(n - 1) + newFib(n - 2) + newFib(n - 3); }} a) 3 b) 5 c) 7 d) 9
d
89) Suppose we wrote a new version of method fib, called newFib. Compare newFib to the original fib shown below: public static long newFib(int n) { if (n <= 3) { return 1; } else { return newFib(n - 1) + newFib(n - 2) + newFib(n - 3); } } public static long fib(int n) { if (n <= 2) { return 1; } else { return fib(n - 1) + fib(n - 2); } } For which values of the integer n does newFib(n) always returns a value greater than fib(n)? a) any positive n b) any value of n c) n >= 3 d) n > 3
d
94) Complete the following code snippet, which is intended to print out all permutations of the string generate by using a permutation generator object. public class PermutationGeneratorTester { public static void main(String[] args) { PermutationGenerator generator = new PermutationGenerator("generate"); ArrayList<String> permutations = generator.getPermutations(); for (String s : permutations) { ____________________ } }} a) generator.print(); b) generator.setPermutations(); c) generator.calculate(); d) System.out.println(s);
d
Computing the sum of the first n integers using the formula n * (n + 1) / 2 has a growth rate _____.
independent of n
Complete the following code snippet, which is intended to be a recursive method that will find the smallest value in an array of double values from index to the end of the array: public static double minVal(double[] elements, int index) { if (index == elements.length - 1) { return elements[index]; } double val = __________________; if (elements[index] < val) { return elements[index]; } else { return val; } } a. minVal(elements, index - 1) b. minVal(index + 1) c. minVal(index - 1) d. minVal(elements, index + 1)
d. minVal(elements, index + 1)
Consider the method below, which implements the exponentiation operation recursively. Select the statement that should be used to complete the method, so that it handles the special case correctly. public static double power(int base, int exponent) { if (exponent == 0) { _______________ } else { return base * power(base, exponent - 1); } } a. return 1 * power(base, exponent - 1); b. return base; c. return 0; d. return 1;
d. return 1;
In recursion, the terminating condition is analogous to a loop _________. a. initialization condition b. iteration c. call d. termination condition
d. termination condition
After a call to remove, the nextPosition data field should be
decremented
The ADT that has operations to add, remove, or retrieve entries at both the front and back of a queue is called a _____.
deque
When a linked chain contain nodes that reference both the next node and the previous node, it is called a _____.
doubly linked chain
When a linked chain contain nodes that reference both the next node and the previous node, it is called a(n)
doubly linked list
The method for adding a new item to the back of a queue is called _____.
enqueue
What type of behavior defines a queue?
first-in first-out
Consider the following code snippet for recursive addition: int add(int i, int j) { // assumes i >= 0 if (i == 0) { return j; } else { return add(i - 1, j + 1); } } Identify the terminating condition in this recursive method.
i == 0
______6) Consider the sort method for selection sort shown below: public static void sort (int[] a) for (int i = 0; i < a.length - 1; i++) int minPos = minimumPosition(i); swap(minPos, i); Suppose we modify the loop control to read int i = 1; i < a.length - 1; i++. What would be the
if (a [i] > a [maxPos] ) { maxPos = i;}
_____ statements are used to add libraries of code to your program.
import
In a circular linked chain, when a node is removed from the queue
it is deallocated
Stacks exhibit which type of behavior?
last-in first out
Stacks exhibit which type of behavior? a.first-in, first out b.first-in, last out c.last-in, first out d.last-in, last out
last-in, first out
Consider the code for the recursive method printSum shown in this code snippet, which is intended to return the sum of digits from 1 to n: public static int printSum(int n) { if (n <= 0) // line #1 { return 0; // line #2 } else { return (n + printSum(n)); //line #3 } } Which of the following statements is correct?
line #3 is incorrect, and should be changed to return (n + printSum(n - 1));
Consider the getArea method shown below. public int getArea() { if (width <= 0) { return 0; } // line #1 else if (width == 1) { return 1; } // line #2 else { Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } } Where is/are the recursive call(s)?
line #4
The following code is an example of a ___ search. public static int search(int[] a, int v) { for (int i = 0; i < a.length; i++) { if (a[i] == v) { return i; } } return -1; }
linear
A linked chain whose last node is null is sometimes called a _____.
linear linked chain
A linked chain whose last node is null is sometimes called a(n)
linear linked chain
Consider the getArea method below. public int getArea() { if (width <= 0) { return 0; } // line #1 else if (width == 1) { return 1; } // line #2 else { Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } } Where is/are the terminating condition(s)?
lines #1 and #2
The operation to retrieve the top entry of a stack without removing it is called a(n) a.peek b.pop c.look d.top
peek
The _____ and _____ methods throw a _____ exception when the stack is empty.
pop; peek; runtime
Reverse polish notation is another term for _____.
postfix expression
Reverse polish notation is another term for a(n) a.postfix expression b.prefix expression c.infix expression d.algebraic expression
postfix expression
Polish notation is another term for a(n) a.prefix expression b.postfix expression c.infix expression d.algebraic expression
prefix expression
Polish notation is another term for _____.
prefix notation
Graph ADT implementations: adjacency lists
private List<List<Integer>> adjacencyLists An adjacency list for a given vertex represents only those edges that originate from the vertex. For a sparse graph, an adjacency list uses less memory than an adjacency matrix. For a dense graph, an adjacency matrix can be the better choice. Using adjacency lists, you can find all the neighbors of a particular vertex by traversing a list. If you want to know whether an edge exists between any two given vertices, you need to search a list. If the graph contains n vertices, each of these operations is O(n) a worst, but is faster on average.
Implement an efficient search method for searching an array of strings if a target value is much more likely to be found close to the beginning or to the end of the array, and less likely in the middle of the array.
private static int searcgBothEnds (String [] a, String target) { int i = 0, j = a.length -1;. while (i <=j) { if (target.equals (a[i])) return i; if (target.equals(a[j])) return j; i++; j--; } return -1; }
You should express the complexity of an algorithm in terms of its _____.
problem size
During program execution, the _____ references the current instruction.
program counter
During program execution, the _____ references the current instruction. a.program counter b.stack c.frame d.activation record
program counter
Consider the following class: public class Address implements Comparable<Address> { private String street; private int number; < constructors and methods not shown > } (a) Write a compareTo method for this class. First compare addresses alphabetically by street; if the streets are the same, then compare the numbers. (b) Override Object's equals method in Address in a manner compatible with the compareTo method.
public int compareTo(Address other) { int diff = street.compareTo(other.street); if (diff ==0) diff = number - other.number; return diff; } public boolean equals (Object obj) { if (! obj instanceof Address)) return false; return compareTo ((Address) obj) == 0;
The code below shows a method from the Quicksort class: private static void recursiveSort(double[] a, int from, int to) { if (from >= to) return; int p = (from + to ) / 2; // Partition: int i = from; int j = to; while (i <= j) { if (a[i] <= a[p]) i++; else if (a[j] >= a[p]) j--; else { swap (a, i, j); i++; j--; } } // Place the pivot in its correct position: if ( ____________________________ ) { _______________________________________ ; _______________________________________ ; } else if ( ____________________________________ ) { _______________________________________ ; _______________________________________ ; } // Sort recursively: _________________________________________ ; _________________________________________ ; } Fill in the blanks.
public static void recursiveSort(double [] a, int from, int to) { if (from >= to) return; int p = (from + to) /2; int i =from; int j = to; while (i <= j) { if (a [i] <= a [p]) j--; else { swap (a,i,j); i++ j--; } } if (p <j ) { swap (a,j,p); p =j; } else if (p>i) { swap (a,i,p); p = i; } recursiveSort (a, from, p-1); recursiveSort (a, p+1,to);
Fill in the blanks in the following implementation of Selection Sort: public static void selectionSort(int[] a) { for (int n = ______________________________________ ) { for (int i = _______________________________________ ) { if ( ____________________________________ ) swap( ____________________________________ ); } } } swap(a, i, j) swaps a[i] and a[j].
public static void selestionSort (int [] a) { for (int n = a.length -1; n >0; n--) for (int =0; i <n ; i++) if (a [i] > a [n] swap (a,i,n);
Add an entry to the stack
push
The operation to add an entry to a stack is called a(n) a.push b.add c.put d.peek
push
The _____ ADT organizes its entries according to the order in which they were added.
queue
statements can be executed repeatedly depending on particular condition(s)
repetition
A string in Java is not a primitive data type.
string
To convert an infix expression to a postfix expression a.scan the infix expression left to right b.scan the infix expression right to left c.search for all of the operators first d.search for all of theoperands first
scan the infix expression left to right
different statements can be executed depending on particular condition(s)
selection
Selecting the smallest element of an array and swapping it with the smallest entry is an operation in which sorting method?
selection sort
statements are executed one after another in order
sequence
What type of algorithm places elements in order?
sorting
The memory required to run an algorithm is called _____.
space complexity
A nested if structure in Java can be replaced by a _____ statement.
switch
In a linked chain implementation of a queue, an external reference to the last node in the chain is called a _____.
tail reference
In a linked chain implementation of a queue, an external reference to the last node in the chain is called a(n)
tail reference
To efficiently remove a node at the end of a linked chain implementation of a queue requires as
tail reference
In the program stack, the record at the top of the stack belongs to the method a.that is currently executing b.that is scheduled to execute next c.that called the method that is currently executing d.none of the above
that is currently executing
The most significant contributor to an algorithm's time requirement is _____.
the algorithm's basic operations
The node that is easiest to access in a linked-chain is _____.
the head node
In the linked chain implementation of a queue, the chain's tail last node contains
the queue's back entry
In the linked chain implementation of a queue, the chain's first node contains
the queue's front entry
In the linked chain implementation of a queue, the chain's first node contains_____.
the queue's front entry
In each iteration, selection sort places which element in the correct location?
the smallest element notyet placed in prior iterations
Consider the sort method shown below for selection sort: public static void sort (int[] a) for (int i = 0; i < a.length - 1; i++) int minPos = minimumPosition(i); swap(minPos, i);
the sort would not consider the first array element
Suppose we modify the loop condition to read i < a.length. What would be the result?
the sort would produce correct results
Consider the sort method shown below for selection sort: public static void sort(int[] a) { for (int i = 0; i < a.length - 1; i++) { int minPos = minimumPosition(i); swap(minPos, i); } }
the sort would work but run one more iteration
When you remove an item from a stack, you remove it from a.the top b.the bottom c.the middle d.wherever the client specifies
the top
The code segment below is designed to add the elements in an array of integers. Select the expression needed to complete the code segment so that it calculates the running time elapsed. long start = System.currentTimeMillis(); int sum = 0; for (int k = 0; k < values.length; k++) sum = sum + values[k]; long runningTime = ____________________________; a) System.currentTimeMillis() b) System.currentTimeMillis() - start c) System.currentTimeMillis() + start d) runningTime + start - System.currentTimeMillis()
the total number of element visits
Assume we are using quicksort to sort an array in ascending order. What can we conclude about the elements to the left of the currently placed pivot element?
they are all less than or equal to the pivot element
When resizing an array to increase the bag size, if the copy exceeds the maximum memory specified for the computer, the checkCapacity method should _____.
throw an IllegalStateException
A measure of an algorithm's execution speed is called _____.
time complexity
Suppose you wish to sort an array list of objects, but the object class does not implement the Comparable interface. Because you are not allowed to modify this class, you decide to provide a comparator object that implements the Comparator interface. Which method must you implement from this interface to achieve your objective?
to compare method