Programming Fundamentals III Java FINAL
when determining whether a number is inside a range, its best to use
&&
Partitioning. Determine the index j and the left and right partitions. numbers = (1, 2, 3, 4, 5), i = 0, k = 4. j=(k+i)/2 Left partition =
(1,2,3). (Elements at indices from i to j, inclusive, are in the left partition.
Partitioning. Determine the index j and the left and right partitions. numbers = (34, 78, 14, 23, 8, 35), i = 3, k = 5, j = (k+1)/2 Left Partition =
(23,8). (i to j)
Partitioning. Determine the index j and the left and right partitions. numbers = (1, 2, 3, 4, 5), i = 0, k = 4, j=(k+i)/2 Right partition =
(4,5) j=j+1 to k
The runtime can be expressed by the series N + (N - 1) + (N - 2) + ... + 3 + 2 + 1. Which expression is mathematically equivalent? (N/2) * (N+1) N*LOG2N
(N/2) * (N+1). (The series contains N / 2 pairs, each summing to N + 1).
An empty binary tree has height
-1
When inserting an element in the middle of the list the following needs to be done (not necessarily in this order): 1) check if list is full and insert index valid 2) update the count 3) place the new element in the array 4) move the elements from insert index one cell up What is a possible correct order of these operations?
1,4,3,2
Assume insertion sort's goal is to sort in ascending order. Given list (10, 11, 12, 13, 14, 5), how many comparisons will be made during the third outer loop execution (i = 3)?
1. (Elements are already sorted.)
How many partitioning "levels" are required for a quicksort list of 1024 elements?
10 (512, 256, 128, 64, 32, 16, 8, 4, 2, 1. )
Next step in sorting this array with quick-sort is (assume that bold element is the pivot and underlined elements are pointed to with the up and down index respectively) 10 3 1 79 4 88 2 33 44 34
10 3 1 2 4 88 79 33 44 34
How many times longer will sorting a list of 500 elements using Selection Sort take compared to a list of 50 elements?
100 (500^2 / 50^2 = 250000 / 2500 or 4)
How many partitioning "levels" are required for a quicksort list of 1024 elements?
1023. Worst case 1024-1.
Answer the following questions assuming each comparison takes 1 µs. Given a list of 1024 elements, what is the runtime for linear search if the search key is less than all elements in the list?
1024
How many total comparisons are required to sort a quicksort list of 1024 elements?
10240
Given list: [20, 4, 114, 23, 34, 25, 45, 66, 77, 89, 11]. How many list elements will be checked if the search key is not found using linear search?
11
pivot = numbers[midpoint] midpoint = i + (k - i) / 2 Determine the pivot value. numbers = (200, 11, 38, 9), i = 0, k = 3
11
How many recursive partitioning levels are required for a list of 2048 elements?
11 (log2(2048)=11)
Which function is an upper bound for the algorithm? 12N^2 5N^2 7N.
12N^2. 12N^2 >= 5N^2 + 7N & 12N^2 >= 3N + 6.
Assume insertion sort's goal is to sort in ascending order. Given list (20, 14, 85, 3, 9), what value will be in the 0th element after the first pass over the outer loop (i = 1)?
14
Trace the merge operation by determining the next value added to mergedNumbers. 14 18 35 17 38 49 leftPos = 0, rightPos = 3.
14. (0=14 3=17. 14<=17 True. 14.)
Trace the merge operation by determining the next value added to mergedNumbers. 14 18 35 17 38 49 leftPos = 1, rightPos = 3.
17. (1=18 3=17. 18<=17 False. 17.)
Trace the merge operation by determining the next value added to mergedNumbers. 14 18 35 17 38 49 leftPos = 1, rightPos = 4.
18. (1=18 4=38. 18<=38 True. 18.)
Given list: ( 4, 11, 17, 18, 25, 45, 63, 77, 89, 114 ). How many list elements will be checked to find the value 77 using binary search?
2
How many list items are compared to the key by binary_search() for each example? List: [12, 18, 22, 34, 41, 74, 88]Key: 74.
2
How many recursive calls of quick-sort do you need to have in your quick-sort code? Select the best (not just a possible) answer.
2
In the Hanoi tower 3 ring scenario If the small ring is on the stick 1, middle ring is on the stick 2 , and the large ring is the stick 3 what is the minimal number of steps required to complete the tower? (your choice of which stick the tower is finally built on).
2
Merge Sort Partitioning. Determine the index j and the left and right partitions. numbers = (1, 2, 3, 4, 5), i = 0, k = 4. (k+i)/2
2
Given a list of 10,000 elements, and if each comparison takes 2 µs, what is the fastest possible runtime for linear search?
2 ms
def merge_sort(numbers, i, k): j = (i + k) // 2 If merge_sort is called with i = 0 and k = 5, what is the value of j after the following line executes?.
2.
For each question, assume a list with 6 elements. With a gap value of 3, how many items will be in each interleaved list? 1,2,3,6.
2. (6 items divided by 3 lists).
For each question, assume a list with 6 elements. If a gap value of 2 is chosen, how many interleaved lists will be sorted?
2. (Gap value determines the number of lists).
Given a list of 10,000 elements, and if each comparison takes 2 µs, what is the longest possible runtime for linear search?
20000 ms
What does FibonacciNumber(8) return?
21 (Sum last 2 digits of first 8 0 - 0 - 1 - 2 - 3 - 5 - 8 - 13. 8+13=21)
O ( 2^n*n^2) =
2^n*n^2
Which of the following complexity categories are ordered from the slowest to the fastest?
2^n, n^5, n * log (n)
Given list: ( 4, 11, 17, 18, 25, 45, 63, 77, 89, 114 ). How many list elements will be checked to find the value 17 using binary search?
3
Given list: [20, 4, 114, 23, 34, 25, 45, 66, 77, 89, 11]. How many list elements will be checked to find the value 114 using linear search?
3
pivot = numbers[midpoint] midpoint = i + (k - i) / 2 Determine the pivot value. numbers = (1, 2, 3, 4, 5), i = 0, k = 4
3 ((0+4-0)/2 = 2. Numbers[2] = 3)
For each question, assume a list with 6 elements. With a gap value of 3, how many interleaved lists will be sorted? 1, 2, 3, 6.
3. (Gap value determines the number of lists).
Assume quicksort always chooses a pivot that divides the elements into two equal parts. How many partitioning levels are required for a list of 8 elements?
3. (abcd efgh -> ab cd ef gh -> a b c d e f g h.)
Merge Sort Runtimes How many recursive partitioning levels are required for a list of 8 elements?
3. (abcd)(efgh), (ab)(cd)(ef)(gh), (a)(b)(c)(d)(e)(f)(g)(h) (log2(8)=3)
pivot = numbers[midpoint] midpoint = i + (k - i) / 2 Determine the pivot value. numbers = (55, 7, 81, 26, 0, 34, 68, 125), i = 3, k = 7
34. (numbers[<midpoint>])
Partitioning. Determine the index j and the left and right partitions. numbers = (34, 78, 14, 23, 8, 35), i = 3, k = 5, j=(k+i)/2 Right Partition =
35 (j and k)
Trace the merge operation by determining the next value added to mergedNumbers. 14 18 35 17 38 49 leftPos = 2, rightPos = 4.
35. (2=35 4=38. 35<=38 True. 35)
Trace the merge operation by determining the next value added to mergedNumbers. 14 18 35 17 38 49 leftPos = 3, rightPos = 4.
38. (3=17 4=38. Left empty so right added.)
How many comparisons are performed by linear_search() for each example? List: [12, 75, 18, 22, 94, 16, 22] Key: 22.
4
Using the Big O runtime complexity, how many times longer will sorting a list of 20 elements take compared to sorting a list of 10 elements?
4 (20^2 / 10^2 = 400 / 100 or 4).
Partitioning. Determine the index j and the left and right partitions. numbers = (34, 78, 14, 23, 8, 35), i = 3, k = 5 j =
4. (5+3)/2 = 4.
How many times longer will sorting a list of 20 elements using Selection Sort take compared to sorting a list of 10 elements?
4. (A list with twice as many elements requires 4 times the amount of time.)
If a gap value of 4 is chosen, how many interleaved lists will be sorted? 4 can't be used 2 3 4.
4. (Some lists will have fewer items to sort.)
How many partitioning "levels" of are required for a quicksort list of 5 elements?
4. (a bcde. a b cde, a b c de, a b c d e)
Evaluate the following postfix expression: 4 5 + 7 2 - *
45
In the worst case, assuming each comparison takes 1 µs, how long will insertion sort algorithm take to sort a list of 10 elements?
45. ((1+2+3+4+5+6+7+8+9)*1 = 45.)
Trace the merge operation by determining the next value added to mergedNumbers. 14 18 35 17 38 49 leftPos = 3, rightPos = 5.
49. (Left empty so right added.)
Assume selection sort's goal is to sort in ascending order. Given list (9, 8, 7, 6, 5), what value will be in the 0th element after the first pass over the outer loop (i = 0)?
5
How many comparisons are performed by linear_search() for each example? List: 12, 75, 18, 22, 94, 16, 22 Key: 94
5
If Factorial(6) is called, how many additional calls are made to Factorial to compute the result of 720? Factorial(N) { if (N == 1) return 1 else return N * Factorial(N - 1) }
5 (6*5*4*3*2 = 720)
Given an array with 32 elements, how many list elements will be checked if the key is less than all elements in the list, using binary search?
5. (15->7->3->1->0).
midpoint = i + (k - i) / 2 pivot = numbers[midpoint] Determine the midpoint value. numbers = (55, 7, 81, 26, 0, 34, 68, 125), i = 3, k = 7
5. (3+((7-3)/2).
def merge_sort(numbers, i, k): If merge_sort is called with i = 0 and k = 4, what is the size of the partition that will be sorted?
5. (The k argument is the partition size minus 1, so the partition size is k + 1. 4 + 1 = 5.)
How many elements will the temporary merge list have for merging two partitions with 250 elements each?
500. Must be large enough to hold all elements from both partitions.
Assuming each comparison takes 2 µs, how long will the selection sort algorithm take to sort a list of 50 elements?
5000 (The selection sort algorithm requires N2 comparisons. 50 * 50 * 2µs = 5000 µs)
Suppose BinarySearch(numbers, 0, 7, 42) is used to search the list (14, 26, 42, 59, 71, 88, 92) for key 42. What is the first middle element that is compared against 42? BinarySearch(numbers, low, high, key) { if (low > high) return -1 mid = (low + high) / 2 if (numbers[mid] < key) { return BinarySearch(numbers, mid + 1, high, key) } else if (numbers[mid] > key) { return BinarySearch(numbers, low, mid - 1, key) } return mid }
59 (With integer division, mid = (0 + 7) / 2 = 3. 59 is at index 3 in the list.)
How many comparisons are performed by linear_search() for each example? List: [12, 75, 18, 22, 94, 16, 22]Key: 10.
7
Assume that down and up index in this quick-sort example have crossed. The pivot (bold element) will be swapped with ? 12 3 8 5 9 16 14
9
Given list: [20, 4, 114, 23, 34, 25, 45, 66, 77, 89, 11]. How many list elements will be compared to find 77 using linear search?
9
How many intermediate results are there in Fib (4) recursive algorithm? Count F0 and F1 as 'results' as well, although no actual calculation takes place. Count repeated calculations as well (Hint: draw the tree!)
9
If the above was evaluated via stack, what would be the final two elements on the stack before the final result was evaluated?
9,5
Given the list nums = [[10, 20, 30], [98, 99]], what does nums[1][1] evaluate to?
99
Convert A * (B + C) + D * E to postfix notation.
A B C + * D E * +
How does the character 'A' compare to the character 'B'?
A is less than B
Which of the following is true?
A map allows duplicate keys to be stored; WRONG ANSWER
Direct vs. Indirect Recursion
A method invoking itself is considered to be direct recursion A method could invoke another method, which invokes another, etc., until eventually the original method is invoked again For example, method m1 could invoke m2, which invokes m3, which invokes m1 again This is called indirect recursion It is often more difficult to trace and debug
The hardware running the code is the only thing that affects what is and what is not a constant time operation. True or False
False
The head of a linked list is also a linked list.
False
The index of an element to be removed from a list can be the same as the size of the list.
False
The last item in a doubly linked list can sometimes have a successor
False
The list is sorted into ascending order:(3, 9, 44, 18, 76).
False
The size of a list is determined when the list is created and can not change. True or False
False
The statement del my_list[2] produces a new list without the element in position 2. True or False.
False
Two different algorithms that produce the same result have the same computational complexity. True or False
False
n factorial (n!) is commonly implemented as a recursive function due to being easier to understand and executing faster than a loop implementation. True or False
False
The predecessor of a node in a binary tree is called its
parent
What typically happens when the last element of a queue is in the MAX array cell, and we need to add yet another element?
place the new element in array cell [1]
A linked list class uses a Node class with successor reference next, and uses a reference first to point to the first node of the list. A positive index k is given, and we want to set a reference pred to point to the node with index k-1. The right code to use is
pred = first; for (int i = 1; i < k; i++) pred = pred.next;
A binary tree traversal method that visits the root first, and then recursively traverses the left and right subtrees is called
preorder traversal
Erasure is the process of
replacing generic types with their upper bound, or with Object, during compilation
In a linked list implementation using a reference first to point to the first node of the list, a method isEmpty() can test to see if the list is empty by executing the statement(s)
return first == null;
explain why a misplaced semicolon can cause an if statement to operate incorrectly
semicolon are used when it is it the end of a statement and java will treat the if statement like a single statement and throw an error or skip over the statements that are meant to be executed within the if statement
A collection that does not impose a positional order on its elements, and does not allow duplicates is called a
set
To remove a node X with index 1 or greater from a linked list
set a reference pred to the predecessor of the node you want to remove, and set the successor of pred to the successor of X
A linked list class uses a Node class with a successor reference next to represent nodes. A private recursive method Node add(int index, E element, Node list) takes a reference list (referring to the first in a chain of Node objects), adds a node containing the given element at the given index, and returns a reference to the first node of the resulting chain. Assume that index is nonnegative and is less or equal to the size of list. Under these circumstances, the add method should handle its non-base case (index is not 0) by
setting list.next to add(index-1, element, list.next) and returning list
Linear Search
simply examines each item in the search pool, one at a time, until either the target is found or until the pool is exhausted This approach does not assume the items in the search pool are in any particular order
To properly advance through all elements of a queue (e.g. to show them) we will most likely employ a(n):
while loop in which we handle the index change abstractly (e.g. via next_ix () function)
Consider the class class Value <T extends Number> { private T v; public Value(T v1) { v = v1; } public void output() { System.out.println(v); } } The code Value<Double> nV1 = new Value<Double>(34.5);
will compile and run correctly
The Vector class
works just like ArrayList, except it is synchronized
Quicksort is not a good candidate for real-time applications because:
worst case time is O (n^2)
Postfix Expressions
written with the operator following the two operands instead of between them: 15 8 - is equivalent to the traditional (infix) expression 15 - 8 Also know as Reverse Polish Notation
Which of the following is a recursive definition?
x^n = x * x^(n-1)
When using a HashSet
you should override the hashCode and equals methods defined in the Object class
Assume that my_list is [0, 5, 10, 15]. What value is returned by min(my_list)?
0
What is the minimum possible size of the returned list? listSize 2, 1, 0. GetEvens(list, listSize) { i = 0 evensList = Create new, empty list while (i < listSize) { if (list[i] % 2 == 0) Add list[i] to evensList i = i + 1 } return evensList }
0 if no even numbers supplied.
How many times is count_down() called if the script calls count_down(0)? def count_down(count): if count == 0: print('Go!') else: print(count) count_down(count-1)
1
Consider the following program: nums = [10, 20, 30, 40, 50] for pos, value in enumerate(nums): tmp = value / 2 if (tmp % 2) == 0: nums[pos] = tmp What's the final value of nums[1]?
10
Given the list nums = [[10, 20, 30], [98, 99]], what does nums[0][0] evaluate to?
10
Assume that my_list is [0, 5, 10, 15]. What value is returned by max(my_list)?
15
scores = [[75,100,82,76], [85,98,89,99], [75,82,85,5]] How many elements does scores contain? (The result of len(scores)).
3 that are lists.
Assume that my_list is [0, 5, 10, 15]. What value is returned by sum(my_list)?
30
Suppose an algorithm's best case runtime complexity is T(N)=3N+6, and the algorithm's worst case runtime is T(N)=5N2+7N. Which function is a lower bound for the algorithm? 5N^2 5N 3N?
3N (3N≤5N2+7N 3N <= 5N^2 + 7N & 3N <= 3N + 6)
How many times is count_down() called if the script calls count_down(5)? def count_down(count): if count == 0: print('Go!') else: print(count) count_down(count-1)
6
Which one of the following has all the correct SHAPE property of Heap? A) 1. All leaves are either at depth d or d-1 (for some value d). 2. All of the leaves at depth d-1 are to the right of the leaves at depth d. 3. (a) There is at most 1 node with just 1 child. (b) That child is the left child of its parent, and (c) it is the rightmost leaf at depth d. B) 1. All leaves are either at depth d or d-1 (for some value d). 2. All of the leaves at depth d-1 are to the left of the leaves at depth d. 3. (a) There is at most 1 node with just 1 child. (b) That child is the left child of its parent, and (c) it is the leftmost leaf at depth d. C) 1. All leaves are either at depth d or d-1 (for some value d). 2. All of the leaves at depth d-1 are to the right go the leaves at depth d. 3. (a) There is at most 1 node with just 1 child. (b) That child is the left child of its parent, and (c) it is the leftmost leaf at depth d. D) None of the above.
A) 1. All leaves are either at depth d or d-1 (for some value d). 2. All of the leaves at depth d-1 are to the right of the leaves at depth d. 3. (a) There is at most 1 node with just 1 child. (b) That child is the left child of its parent, and (c) it is the rightmost leaf at depth d.
Quick sort algorithm outline is: A) 1. Choose a pivot value. 2. Partition the array (put all value less than the pivot in the left part of the array, then the pivot itself, then all values greater than the pivot). 3. Recursively, sort the values less than the pivot. 4. Recursively, sort the values greater than the pivot. B) 1. Choose a pivot value. 2. Partition the array (put all value greater than the pivot in the right part of the array, then the pivot itself, then all values greater than the pivot). 3. Recursively, sort the values less than the pivot. 4. Recursively, sort the values greater than the pivot. C) 1. Choose a pivot value. 2. Partition the array (put all value less than the pivot in the right part of the array, then the pivot itself, then all values greater than the pivot). 3. Recursively, sort the values greater than the pivot. 4. Recursively, sort the values greater than the pivot. D) None of the above
A) 1. Choose a pivot value. 2. Partition the array (put all value less than the pivot in the left part of the array, then the pivot itself, then all values greater than the pivot). 3. Recursively, sort the values less than the pivot. 4. Recursively, sort the values greater than the pivot.
Which of the following algorithms do we use to search a key in BST? A) Algorithm Treesearch(k,v) if v.isExternal () return v if k < v.key() return TreeSearch(k, v.left()) else if k = v.key() return v else {k > v.key()} return TreeSearch(k, v.right()) B) Algorithm TreeSearch(k, v) if v.isExternal() return v if k = v.key() return v else { k > v.key()} return TreeSearch(k, v.right()) C) Algorithm TreeSearch(k, v) if v.isExternal() return v if {k > v.key()} return TreeSearch(k, v.right()) D) Algorithm TreeSearch(k, v) TreeSearch(k, v.left()) else if k = v.key() return v else {k > v.key()} return TreeSearch(k, v.right())
A) Algorithm TreeSearch(k, v) if v.isExternal() return v if k < v.key() return TreeSearch(k, v.left()) else if k = v.key() return v else {key > v.key()} return TreeSearch(k, v.right())
Which of the following has the correct ORDER property of HEAP? A) For every node n, the value in n is less than or equal to the values in its children (and thus is also greater than or equal to all of the values in its subtrees). B) For every node n, the value in n is greater than or equal to the values in its children (and thus is also greater than or equal to all of the values in its subtrees). C) For every node n, the value in n is equal to the values in its children (and thus is also greater than or equal to all of the values in its subtrees). D) This is red and black tree property not heap.
B) For every node n, the value in n is greater than or equal to the values in its children (and thus is also greater than or equal to all of the values in its subtrees).
AVL Tree performance with respect to time complexity is as follows: A) find takes O(n log n) time put takes O(n log n) time erase takes O(n log n) time B) find takes O(log n) time put takes O(log n) time erase takes O(log n) time C) find takes O(log) time put takes O(log) time erase takes O(log) time D) find takes O(n) time put takes O(n) time erase takes O(n) time
B) find takes O(log n) time put takes O(log n) time erase takes O(log n) time
To sort an array of length N using Merge sort following steps must be taken: A) 1. Divide the array into two halves. 2. Recursively, sort the left half. 3. Recursively, sort the left half. 4. Merge the two sorted halves. B) 1. Divide the array into two halves. 2. Recursively, sort the right half. 3. Recursively, sort the left half. 4. Merge the two sorted halves. C) 1. Divide the array into two halves. 2. Recursively, sort the left half. 3. Recursively, sort the right half. 4. Merge the two sorted halves. D) 1. Divide the array into ten halves. 2. Recursively, sort the left half. 3. Recursively, sort the right half. 4. Merge all the sorted halves.
C) 1. Divide the array into two halves. 2. Recursively, sort the left half. 3. Recursively, sort the right half. 4. Merge the two sorted halves.
A binary search tree is a binary tree storing keys (or key-value entries) at its internal nodes by satisfying which of the following: A) Let u, v, and w be three nodes such that u is in the left subtree of v and w is in the right subtree of v. We have key(u) >= key(v) >= key(w) B) Let u, v, and w be three nodes such that u is in the left subtree of v and w is in the right subtree of v. We have key(u) = key(v) = key(w) C) Let u, v, and w be three nodes such that u is in the left subtree of v and w is in the right subtree of v. We have key(u) <= key(v) <= key(w) D) None of the above.
C) Let u, v, and w be three nodes such that u is in the left subtree of v and w is in the right subtree of v. We have key(u) <= key(v) <= key(w)
(T/F) An iterator does not abstract the process of scanning through a collection of objects
F
(T/F) ListIterator is a java iterator, which is used to iterate many elements at a time from a list implemented object.
F
A loop is never a constant time operation. True or False
False
All elements of a list must have the same type. True or False
False
An algorithm's best and worst case scenarios are always different.
False
Assume that my_list is [0, 5, 10, 15]. What value is returned by all(my_list)?
False
In the code below, suppose str1 is a pointer or reference to a string. The code only executes in constant time if the assignment copies the pointer/reference, and not all the characters in the string. True or False str2 = str1
False
Nearly every algorithm has a best case time complexity when N = 0. True or False
False
Runtime and memory usage are the only two resources making up computational complexity. True or False
False
T or F: General-purpose data structures are arrays, linked lists, trees, hash tables, quick sort, and stack
False
T or F: In BST the height h is O(n) in the worst case and O(n log n) in the best case.
False
T or F: ceilingEntry takes O(n log n) time, using binary search.
False
The variable my_dict created with the following code contains two keys, 'Bob' and 'A+'. my_dict = dict(name='Bob', grade='A+'). True or False
False
Dictionaries can contain up to three levels of nesting. True or False
False (arbitrary)
Given the following code: nums = [0,25,50,75,100]: The result of evaluating nums[0:5:2] is [25, 75].
False [0,50,100]. Indexs 0 through 5 stepping 2.
Determine the output of each code segment. If the code produces an error, type None. Assume that my_dict has the following entries: my_dict = dict(bananas=1.59, fries=2.39, burger=3.50, sandwich=2.99). my_dict.update(dict(soda=1.49, burger=3.69)) burger_price = my_dict.get('burger', 0) print(burger_price)
Output: 3.69
What is the worst case space complexity of GetEvens if N is the list's size and k is a constant? S(N) = N + k or S(N) = k? GetEvens(list, listSize) { i = 0 evensList = Create new, empty list while (i < listSize) { if (list[i] % 2 == 0) Add list[i] to evensList i = i + 1 } return evensList }
S(N) = N + k. Worst case is all items.
What is the best case auxiliary space complexity of GetEvens if N is the list's size and k is a constant? S(N) = N + k or S(N) = k? GetEvens(list, listSize) { i = 0 evensList = Create new, empty list while (i < listSize) { if (list[i] % 2 == 0) Add list[i] to evensList i = i + 1 } return evensList }
S(N) = k contains all odds and returns a 0 for best case.
(T/F) A container of an abstract data structure that supports element access through iterators. An iterator abstracts the process of scanning through a collection of elements. begin(): end() An iterator behaves like a pointer to an element *p ++p
T
(T/F) A doubly linked list is a linked days structure that consists a set of sequentially linked records called nodes
T
A program can modify the elements of an existing list. True or False
True
A programmer can iterate over a copy of a list to safely make changes to that list.
True
A recursive function can have two base cases, such as n==0 returning 0, and n==1 returning 1. True or False
True
A recursive function with parameter n counts up from any negative number to 0. An appropriate base case would be n==0. True or False
True
Assume that my_list is [0, 5, 10, 15]. What value is returned by any(my_list)?
True
Certain hardware may execute division more slowly than multiplication, but both may still be constant time operations. True or False
True
Computational complexity analysis allows the efficiency of algorithms to be compared. True or False
True
Dictionary entries can be modified in-place - a new dictionary does not need to be created every time an element is added, changed, or removed. True or False
True
Iterating over a list and deleting elements from the original list might cause a logical program error.
True
Nested dictionaries are a flexible way to organize data. True or False
True
T or F: 234 tree's time complexity is O(log n) regardless of if the data is ordered or unordered
True
T or F: A graph is a pair (V, E), where V is a set of nodes called vertices and E is a collection of pairs of vertices, called edges Vertices and edges are positions and store elements
True
T or F: A heap is a binary tree (in which each node contains a Comparable key value), with two special properties; an ORDER property and SHAPE property.
True
T or F: Algorithms like quick sort -- that work by dividing the problem in two, solving the smaller versions, and then combining the solutions -- are called divide and conquer algorithms.
True
T or F: Binary search can perform operations get, floorEntry and ceilingEntry on an ordered map implemented by means of an array-based sequence, sorted by key.
True
T or F: Following are Adjacency List Structure: Edge list structure *incidence sequence for each vertex sequence of references to edge objects of incident edges Augmented edge objects *references to associated positions in incidence sequences of end vertices
True
T or F: If array and linked list is too slow then we should consider binary search tree
True
T or F: In a directed graph the order of the vertices in the pairs in the edge set matters.
True
T or F: In an undirected graph, the order of the vertices in the pairs in the edge set doesn't matter
True
T or F: Insertion for AVL tree is by expanding an external node
True
T or F: Is the following a valid algorithm for insertion sort? public static void insertionSort(Comparable[] A) { int k, j; Comparable tmp; int N = A.length; for(k = 1; k < N, k++) { tmp = A[k]; j = k -1; while((j >= 0) && (A[j].compareTo(tmp) > 0)) { A[j + 1] = A[j]; //move one value over one place to the right j--; } A[j + 1] = tmp; //insert 4th value in correct place relative to previous values } }
True
T or F: Removal of a node in AVL tree means the node removed will become an empty external node.
True
T or F: Specialized data structures are: stacks, queues, priority queues, graphs
True
T or F: The height f an AVL tree storing n keys is O(log n).
True
T or F: The idea behind selection sort is: 1. Find the smallest value in A; put it in A[0]. 2. Find the second smallest value in A; put it in A[1].
True
T or F: Using the following Heap algorithm we can remove the Max value: 1. Replace the value in the root with the value at the end of the array (which corresponds to the heap's rightmost leaf at depth d). Remove that leaf from the tree. 2. Now work your way down the tree, swapping values to restore the order property: each time, if the value in the current node is less than one of its children, then swap its value with the larger child (that ensures that the new root value is larger than both of its children).
True
The 3 constant time operations in the code below can collectively be considered 1 constant time operation. True or False x = 26.5 y = 15.5 z = x + y
True
The expression {'D1': {'D2': 'x'}} is valid. True or False
True
The statement my_list1 + my_list2 produces a new list. True or False
True
nums = [0,25,50,75,100] The result of evaluating nums[0:-1:3] is [0, 75].
True. Index 0 going backwards stepping 3.
Only negative odd values from the list x.
[(i) for i in x if ((i < 0) and (i % 2 == 1))]
Assume that the following code has been evaluated: nums = [1,1,2,3,5,8,13]. What is the result of nums[1:5]?
[1,2,3,5]
Given the list nums = [[10, 20, 30], [98, 99]], what does nums[0] evaluate to?
[10,20,30]
nums = [1,1,2,3,5,8,13]. What is the result of nums [3:-1]?
[3,5,8
nums = [1,1,2,3,5,8,13]. What is the result of nums[5:10]?
[8,13]
Consider the following function, which builds and returns a list of even numbers from the input list. GetEvens(list, listSize) { i = 0 evensList = Create new, empty list while (i < listSize) { if (list[i] % 2 == 0) Add list[i] to evensList i = i + 1 } return evensList } What is the maximum possible size of the returned list? listSize or listSize / 2.
listSize. If all listSize is even then all will be returned.
The largest square root of any element in x. Use math.sqrt() to calculate the square root.
max([math.sqrt(i) for i in x])
Create a nested list nums whose only element is the list [21, 22, 23].
nums = [[21,22,23]]
1) Assume the following list has been created: scores = [[75,100,82,76], [85,98,89,99], [75,82,85,5]] Write an indexing expression that gets the element from scores whose value is 100.
scores[0][1]
The heap sort method has a worst case complexity function that is in
O(n log n)
A Node class for a linked list that can hold elements of type Object can be declared to have fields
Object element; Node next;
A for loop of the form for (i = 0; i < N; ++i) {} that does not have nested loops or function calls, and does not modify i in the loop will always has a complexity of O(N).
True
ShellSort will properly sort an array using any collection of gap values, provided the collection contains gap value 1. True or False
True
Suppose T(N)=2N2+N+9. T(N) = 0(N^2). True or False.
True
Suppose T(N)=2N2+N+9. T(N) = Ω(N^2). True or False.
True
Suppose T(N)=2N2+N+9. T(N) = θ(N^2). True or False
True
T or F: The last node of a heap is the leftmost node of maximum depth.
False
A Java collection
is an object that is is used as a container for other objects
A TreeSet
is like a Set that allows elements to be retrieved according to their natural order, or according to an order specified by a Comparator
Which of the following does not need to be checked when inserting an element into a simple linear list:
is list empty
The depth of a binary tree
is the length of the longest path from the root to a leaf
Searching
is the process of finding a target element among a group of items (the search pool), or determining that it isn't there This requires repetitively comparing the target to candidates in the search pool An efficient search performs no more comparisons than it has to
In a linked list, the predecessor of a node X
is undefined if X is the first node, otherwise it is the node whose index is one less than the index of X
The tail of a list
is what you get when take a list and remove its head
Which is true for a contiguous list?
it doesn't have any 'holes' (the only blank cells, if any, are at the very end of the array)
find the error: if (average = 100) System.out.println("Perfect Average!")
it is missing an additional ==
why is it good advice to indent all of the statements inside a set of braces
it makes the code easier to read, and it helps the programmer know which statements go with the conditional statement
assume that partNumber references a string object. the following if statement should perform a case-insensitive comparison. what is wrong with it: if (partNumber.equals("BQ789W4")) available = true;
it needs to add IgnoreCase after .equals
the following statement assigns 0 to z if a is less than 10; otherwise it should assign 7 to z. what is wrong with it: z = (a < 10) : 0 ? 7
it should look like: if (a < 10) z = 0; else z = 7;
A circularly linked list makes it easy to
jump from the last node to the first
To remove a node with index 0 from a linked list,
just move the head reference one node forward
Lists
linear collection, like stacks and queues, but is more flexible Adding and removing elements in lists can occur at either end or anywhere in the middle We will examine three types of list collections: ordered lists unordered lists indexed lists
To allocate storage for their elements, linked lists use
linked allocation
A collection that stores its elements in an (ordered) sequence, and allows access to each element by its position in the sequence is called a
list
The three major categories of Java collections are
lists, sets, and maps
A complete binary tree with N nodes has depth approximately equal to
log N
&&, ||, and ! are
logical operators
In Java, the first node in a list has index
0
midpoint = i + (k - i) / 2 pivot = numbers[midpoint] Determine the midpoint value. numbers = (200, 11, 38, 9), i = 0, k = 3
1
Which one of the following number arrangements makes quick-sort slow?
1 2 3 4 5 7 6 12 15
What does FibonacciNumber(2) return? FibonacciNumber(termIndex) { if (termIndex == 0) return 0 else if (termIndex == 1) return 1 else return FibonacciNumber(termIndex - 1) + FibonacciNumber(termIndex - 2) }
1 [((2-1) + (2-2))=1]
Which of the following is true?
A TreeSet created with the no-arg constructor expects its elements to implement the Comparable interface
Collection Abstraction
A class that uses a collection interacts with it through a particular interface
Infinite Recursion
A definition without a non-recursive part causes The non-recursive part is called the base case This problem is similar to an infinite loop -- with the definition itself causing the infinite "looping
In many recursive operations on lists,
All of these
Abstract Data Type
An abstract data type (ADT) is a data type that isn't pre-defined in the programming language
T or F: AVL Tree is a binary search tree such that for every internal node v of T, the heights of the children of v can differ by at most 56.
False
Which of the following is true?
Any iterator can move forward as well as backwards through a collection; WRONG ANSWER
T or F: Following is one of the properties of graph: In an undirected graph with no self-loops and no multiple edges m >= n(n - 1)/2 Proof: each vertex had degree at most (n-1)
False
Scientists in a certain laboratory are working with a linked list class that uses recursion to compute its size. The scientists know that an empty list has size 0, so they never ask a linked list to compute its size when the list is empty. Under these circumstances,
B and C are both correct
A contact list is searched for Bob. Assume the following contact list: Amy, Bob, Chris, Holly, Ray, Sarah, Zoe What is the second contact searched?
Bob
Which of the following is true?
Both the Set and List interfaces extend the Collection interface
Analyzing Loop Execution
Consider the following loop: count = 1; while (count < n) { count *= 2; // some sequence of O(1) steps } The loop is executed log2n times, so the loop is O(log n)
O(5) has a _____ runtime complexity.
Constant
T or F: Java stores only objects, not actual references
False
Recursion vs. Iteration
Every recursive solution has a corresponding iterative solution A recursive solution may simply be less efficient Furthermore, recursion has the overhead of multiple method invocations However, for some problems recursive solutions are often more simple and elegant to express
Consider Fibonacci numbers. Knowing the following is enough to calculate F(5):
F(4) and F(3)
A linked list is a looping data structure
False
Suppose BucketSort is called to sort the list (71, 22, 99, 7, 14), using 5 buckets. 71 and 99 will be placed into the same bucket. True or False
False (71 is placed into bucket 2, since floor(71 * (5 - 1) / 99) = 2.99 is placed into bucket 4, since floor(99 * (5 - 1) / 99) = 4. Number * (Buckets-1) / Max Number)
Determine if the low and high partitions are correct given h and pivot. 5(P),13(H),16,77,84,20,19. True or False.
False (13!<=5)
Suppose ReverseList is called on a list of size 3, a start index of 0, and an out-of-bounds end index of 3. The base case ensures that the function still properly sorts the list. ReverseList(list, startIndex, endIndex) { if (startIndex >= endIndex) return else { Swap elements at startIndex and endIndex ReverseList(list, startIndex + 1, endIndex - 1) } }
False (A base case is not synonymous with an error-checking case. Because 0 is less than 3, ReverseList would encounter the non-base case, attempt to swap at indices 0 and 3, and would therefore access the list out of bounds.)
The presence of a base case is what identifies an algorithm as being recursive.
False (A recursive algorithm is identified by the presence of a step wherein the algorithm applies itself to a smaller subproblem.)
A recursive algorithm applies itself to a smaller subproblem in all cases.
False (In the base case, the recursive algorithm completes without applying itself)
List Partitioning. Uses the partition() in class material The value 15 would be selected as the pivot in the list:[5, 3, 15, 72, 14, 41, 32, 18]. True or False
False. (Middle value rounded down if an even list.)
The list [12, 75, 18, 22, 94, 16, 22] can be used as input to the binary_search() function.
False. (Must be in sorted order for Binary Search).
def merge_sort(numbers, i, k): Merge Sort in Python To sort a list with 10 elements, the arguments passed to merge_sort will be: list, 0, 10.
False. (The third argument must be the list size minus 1. 10 - 1 = 9, so the arguments should be: list, 0, 9.)
If the insertion_sort_interleaved() function runs with a list of size 10, start_index assigned with 2, and gap assigned with 3, then the loop variable i will be assigned with the values 2, 5, and 8. i = start_index+gap True or False
False. (i = start_index+gap = 5).
Analyzing Loop Execution
First determine the order of the body of the loop, then multiply that by the number of times the loop will execute for (int count = 0; count < n; count++) // some sequence of O(1) steps N loop executions times O(1) operations results in a O(n) efficiency
Which of the following Big O notations is equivalent to O(12·N +6·N3 + 1000)? O(1000) O(N) O(N^3)
O(N^3). O(12·N + 6·N3 + 1000) = O(6·N3) = O(N3)
Which of the following statements is true?
Generic types do not exist at the byte code level.
Abstraction
Hides details to make a concept easier to manage All objects are abstractions in that they provide well-defined operations (the interface) They hide (encapsulate) the object's data and the implementation of the operations An object is a great mechanism for implementing a collection
A contact list is searched for Bob. Assume the following contact list: Amy, Bob, Chris, Holly, Ray, Sarah, Zoe What is the first contact searched using Binary Search?
Holly
A method int size( ) in a linked list class returns the number of elements stored in the list by executing the single statement return count; For this to work correctly,
It is not possible for size to just return the count value: the size method must set count to 0 and then increment count once for each element in the list.
In a Map object
It is possible for a single value to appear more than once, with different keys
Radix Sort
Let's look at one other sorting algorithm, which only works when a sort key can be defined Separate queues are used to store elements based on the structure of the sort key For example, to sort decimal numbers, we'd use ten queues, one for each possible digit (0 - 9) To keep our example simpler, we'll restrict our values to the digits 0 - 5 The radix sort makes three passes through the data, for each position of our 3-digit numbers A value is put on the queue corresponding to that position's digit Once all three passes are finished, the data is sorted in each queue
Is there a difference in how we define the parameters of a recursive versus non-recursive function? Answer yes or no.
No
O(N log N) has a _____ runtime complexity.
Log-linear
Suppose a recursive function's runtime is T(N)=7+T(N−1). How many levels will the recursion tree have? 7 LOG2N N
N (The input size is only reduced by 1 for each call, so N recursive calls are needed and the recursion tree will have N levels.)
What is the condition for the base case in the CumulativeSum function? CumulativeSum(N) { if (N == 0) return 0 else return N + CumulativeSum(N - 1) }
N == 0.
Suppose a recursive function's runtime is T(N)=N+T(N−1). How many levels will the recursion tree have? LOG2N N N^2.
N. (The input size is only reduced by 1 for each recursive call, so N recursive calls are needed, and the recursion tree will have N levels.)
Determine if each of the following lists is unsorted, sorted, or nearly sorted. Assume ascending order. (23, 24, 36, 48, 19, 50, 101)
Nearly Sorted
A linked list class uses a Node class with successor reference next and field element to store values. It uses a reference first to point to the first node of the list. Code to print all elements stored in the list can be written as
Node p = first; while (p != null) { System.out.println(p.element); p = p.next; }
The clause catch(Exception<T> e) { }
None of the above
The concrete classes that implement the List interface are
None of the above; WRONG ANSWER
Asymptotic Complexity
Not typically necessary to know the exact growth function for an algorithm We are mainly interested in the asymptotic complexity of an algorithm - the general nature of the algorithm as n increases Based on the dominant term of the growth function - the term that increases most quickly as n increases
A linear search has a _____ runtime complexity.
O(N).
What is the runtime complexity of the function using O notation? O(N) O(1) (Best Case runtime) O(LogN)
O(N). (The recursion tree has N levels and does a constant number of operations at each level, making the time complexity O(N).)
Which of the following Big O notations is equivalent to O(734·N)? O(N) O(734) O(734*N^2).
O(N). Constants in product terms are omitted. For O(734·N), the constant 734 is omitted, yielding O(N).
Which of the following Big O notations is equivalent to O(N+9999)? 0(1) O(N) 0(9999).
O(N). For O(N+9999), N is the highest order term, yielding O(N)
A selection sort has a _____ runtime complexity.
O(N^2)
Determine the simplified Big O notation. 10 · O(N2).
O(N^2)
Determine the simplified Big O notation. 10 + O(N^2).
O(N^2).
1) Determine the simplified Big O notation. 2*N^3+O(N2)
O(N^3)
Determine the simplified Big O notation. 3 * N * O(N^2).
O(N^3).
Determine the output of each code segment. If the code produces an error, type None. Assume that my_dict has the following entries: my_dict = dict(bananas=1.59, fries=2.39, burger=3.50, sandwich=2.99) my_dict['burger'] = my_dict['sandwich'] val = my_dict.pop('sandwich') print(my_dict['burger'])
Output: 2.99
Postfix Expressions2
Postfix expressions eliminate the need for parentheses to specify the order of operations The infix expression (3 * 4 - (2 + 5)) * 4 / 2 is equivalent to the postfix expression 3 4 * 2 5 + - 4 * 2 /
5 Stack Operations
Push, Pop, Peek, isEmpty, size
O(N + N2) has a _____ runtime complexity.
Quadratic
Comparing Sorts
Selection sort, insertion sort, and bubble sort use different techniques, but are all O(n2) They are all based in a nested loop approach In quick sort, if the partition element divides the elements in half, each recursive call operates on about half the data The act of partitioning the elements at each level is O(n) The effort to sort the entire list is O(n log n) It could deteriorate to O(n2) if the partition element is poorly chosen Merge sort divides the list repeatedly in half, which results in the O(log n) portion The act of merging is O(n) So the efficiency of merge sort is O(n log n) Selection, insertion, and bubble sorts are called quadratic sorts Quick sort and merge sort are called logarithmic sorts
Determine if each of the following lists is unsorted, sorted, or nearly sorted. Assume ascending order. (15, 19, 21, 24, 2, 3, 6, 11)
Unsorted
Growth Function
Shows the relationship between the size of the problem (n) and the value optimized (time)
Determine if each of the following lists is unsorted, sorted, or nearly sorted. Assume ascending order. (6, 14, 85, 102, 102, 151)
Sorted
Generics
Suppose we define a stack that holds Object references, which would allow it to hold any object But then we lose control over which types of elements are added to the stack, and we'd have to cast elements to their proper type when removed A better solution is to define a class that is based on a generic type The type is referred to generically in the class, and the specific type is specified only when an object of that class is created
You can use this method to display formatted output in a console window.
System.out.printf
Which function is a recurrence relation?
T(N) = 6N +T(N/4). (Has T in both sides of equation.)
Which of the following is true?
The ListIterator interface is a subinterface of the Iterator interface
Which of the following is true?
The Map interface does not extend the Collection interface
In a linked list, the successor of a node X
may not exist
Big-Oh Notation
The coefficients and the lower order terms become increasingly less relevant as n increases So we say that the algorithm is order n2, which is written O(n2) This is called Big-Oh notation There are various Big-Oh categories Two algorithms in the same category are generally considered to have the same efficiency, but that doesn't mean they have equal growth functions or behave exactly the same for all values of n
Generics
The generic type placeholder is specified in angle brackets in the class header: class Box<T> { // declarations and code that refer to T } Any identifier can be used, but T (for Type) or E (for element) have become standard practice. Then, when a Box is needed, it is instantiated with a specific class instead of T: Box<Widget> box1 = new Box<Widget>(); Now, box1 can only hold Widget objects The compiler will issue errors if we try to add a non-Widget to the box And when an object is removed from the box, it is assumed to be a Widget Using the same class, another object can be instantiated: Box<Gadget> box2 = new Box<Gadget>(); The box2 object can only hold Gadget objects Generics provide better type management control at compile-time and simplify the use of collection classes
Which of the following is true of a HashSet object?
The time required to add an element, or search for an element, increases as the number of collisions increases
In our parentheses checking program which of the following errors cannot be detected in the scanner loop?
Too many open parentheses
The base case is what ensures that a recursive algorithm eventually terminates.
True
The complexity of the algorithm below is O(1). if (timeHour < 6) { tollAmount = 1.55 } else if (timeHour < 10) { tollAmount = 4.65 } else if (timeHour < 18) { tollAmount = 2.35 } else { tollAmount = 1.55 }
True
The complexity of the algorithm below is O(1). for (i = 0; i < 24; ++i) { if (timeHour < 6) { tollSchedule[i] = 1.55 } else if (timeHour < 10) { tollSchedule[i] = 4.65 } else if (timeHour < 18) { tollSchedule[i] = 2.35 } else { tollSchedule[i] = 1.55 } }
True
The list is sorted into ascending order:(chopsticks, forks, knives, spork)
True
The list is sorted into ascending order:(great, greater, greatest)
True
The list is sorted into descending order:(20, 15, 10, 5, 0).
True
The list is sorted into descending order:(99.87, 99.02, 67.93, 44.10)
True
The list is sorted into descending order:(F, D, C, B, A)
True
Determine if the low and high partitions are correct given h and pivot. 1,4,35(h),62,98. pivot = 35. True or False.
True (1,4,35<=35<=62,98)
Determine if the low and high partitions are correct given h and pivot. 29,17,65(P),39(H),84. True or False. 17,29,39,65 <=65<=84
True. (17,29,39,65<=65<=84)
Determine if the low and high partitions are correct given h and pivot. 8,3,8(H)(P),41,57,8. True or False
True. (8,3,8<=8<=8,41,57
3N + 6 is a lower bound for the algorithm. True or False
True. An algorithm's best case runtime complexity is always a lower bound for the algorithm.
5N^2 + 7N is an upper bound for the algorithm. True or False.
True. An algorithm's worst case runtime complexity is always an upper bound for the algorithm.
Analyzing Nested Loops
When loops are nested, we multiply the complexity of the outer loop by the complexity of the inner loop for (int count = 0; count < n; count++) for (int count2 = 0; count2 < n; count2++) { // some sequence of O(1) steps } Both the inner and outer loops have complexity of O(n) The overall efficiency is O(n2)
Which is a reasonable choice for gap values, given an input list of size 75? [1,3,7,15,31], [31,15,7,3,1], [1,2,3].
[31,15,7,3,1]. (Powers of 2 minus 1 is a common choice, in decreasing order. 1 should be the last value.)
The absolute value of each element in x. Use the abs() function to find the absolute value of a number.
[abs(i) for i in x]
Write a list comprehension that contains elements with the desired values. Use the name 'i' as the loop variable. Use parentheses around the expression or condition as necessary. Only negative values from the list x:
[i for i in x if i < 0]
Twice the value of each element in the list variable x.
[i*2 for i in x]
A binary tree stores items that have a natural order in such a way that at each node X, all items stored in the left subtree of X are less than the item stored at X, and all items stored in the right subtree are greater than the item stored at X. Such a binary tree is called
a binary search tree
An AVL tree is
a binary search tree in which the heights of the subtrees at each node differ by at most one
Queues
a collection whose elements are added on one end and removed from the other Therefore a queue is managed in a FIFO fashion: first in, first out Elements are removed in the same order they arrive Any waiting line is a queue: the check out line at a grocery store the cars at a stop light an assembly line
In a typical circular doubly linked list, a node has
a field to store the element, and two references to keep track of successor and predecessor nodes
In a typical doubly linked list, a node has
a field to store the element, and two references to keep track of successor and predecessor nodes
A node in a binary tree that has no children is called
a leaf
A list in which each stored element is associated with a reference to its successor is called
a linked list
A collection whose elements are pairs of keys and values is called
a map
If you try to add an item to an ArrayList whose size is equal to its capacity,
a new ArrayList object with twice the capacity is created, and the elements are moved to this new ArrayList.
The Josephus Problem
a set of elements are arranged in a circle Starting with a particular element, every ith element is removed Processing continues until there is only one element left The question: given the starting point and remove count (i), which element is left?
A systematic procedure for starting at the first node in a list, and visiting all nodes in the list by going from each node to its successor is called
a traversal
Assuming the Stack is not empty, POP() Means: a.) Remove the top element from the stack b.) Insert an element from the top of the stack c.) Return the number of elements in stack d.) Remove the last element in stack
a.)
For expression such as this : 12+3^14-2 in order to convert it to postfix to perform stack calculation, we need the following extension to the basic algorithm (your homework).
add exponentiation operation introduce extra parentheses before conversion to postfix use special symbol as a delimiter Correct Answer all of the above
A linked list class uses a Node class to represent nodes. A private recursive method Node add(int index, E element, Node list) takes a reference list (referring to the first in a chain of Node objects), adds a node containing the given element at the given index, and returns a reference to the first node of the resulting chain. Assume that index is nonnegative and is less than or equal to the size of list. Under these circumstances, the add method should handle its base case (index is 0) by
adding a node containing element to the front of list and returning a reference to the newly created node
how often must you place break; statements when using a switch statement
after every case and the default
An object that is used to retrieve objects from a collection is called
an accessor; WRONG ANSWER
The generic method public static <E extends Number> void displayArray(E[] array) { for (E element : array) System.out.println(element); } can be passed
an array whose element type is Integer
what happens when you compare two string objects with the == operator
an error will occur. you have to use .equals for strings
Collection
an object that holds and organizes other objects It provides operations for accessing and managing its elements
briefly describe how the && operator works
answers may vary. use your own words
briefly describe how the || operator works
answers may vary. use your own words
Sequential sorts
approximately n^2 comparisons to sort n elements
Exceptions of a generic type
are not permitted in Java
A LinkedHashMap
can be set up to maintain its keys in insert or access order
A generic class
can extend generic and non-generic classes
When a generic class is instantiated without specifying an actual type argument, the generic class is being used
as a raw type
To remove a node with a positive index k from a linked list
assign the successor reference in the node with index k to the successor reference in the node with index k-1
The automatic conversion of a primitive type to the corresponding wrapper type when being passed as parameter to a generic class is called
autoboxing
The declaration ArrayList<int> aL = new ArrayList<int>();
causes a compile-time error
The successor of a node in a binary tree is called its
child
A queue is a container of elements that are inserted and removed according to the _____________. a.) FOFI b.) FIFO c.) FOFI d.) OFIF
b.)
A stack is a container of object that are inserted and removed according to the _____________. a.) FIFO b.) LIFO c.) LILO d.) LIOF
b.)
What is contiguous memory allocation? a.) When vector allocates memory dynamically its called contiguous memory allocation. b.) Implementation of lists can be array-based, this is known as contiguous memory allocation. c.)Implementation of queues can be array-based, this is known as contiguous memory allocation. d.)None of the above
b.)
Why is the Bubble sort n^2 (considering that inner loop doesn't go all the way to n)?
because O (1+2+3+...n) = n^2
in a generic method, a type parameter is defined
before the method's return type
The if statement is an example of a __________.
decision structure
This section of a switch statement is branched to if none of the case expressions match the switch expression.
default
A binary tree is a collection of nodes in which
each node has at most one predecessor and at most two successors
This type of expression has a value of either true or false.
boolean expression
to create a block of statements, you enclose statements in these
braces
Recursion typically involves:
breaking a large problem into smaller problems of the same type heavy use of internal stack function calling itself Correct Answer all of the above
A linked list class keeps its elements in the order in which they are added, with the index of an element X being greater than the index of any element added to the list before X. Addition of new elements to such a list can be made more efficient
by keeping a reference to the last element added
In Stack, Push (e) Means: a.) Remove the top element b.) Return e from the stack c.) Insert element e at the top of the stack d.) Insert element e at the bottom of the stack
c.)
explain what is meant by the phrase "conditionally executed"
conditionally executed means that the statements will not execute if the condition preceding it is false
To allocate storage for its elements, an array-based list such as ArrayList uses
contiguous allocation
A method int size( ) in a linked list class returns the number of elements stored in the list by executing the single statement return count; For this to work correctly,
count must be an instance variable in the class, initialized to 0, incremented by each add method, and decremented by each remove method
Indexed Lists
elements are referenced by their numeric position in the list Like an unordered list, there is no inherent relationship among the elements The user can determine the order Every time the list changes, the indexes are updated
Binary Search
eliminates large parts of the search pool with each comparison
Silent error reporting:
enables the main program (calling the error-detecting function ) to handle the error as it sees fit
The process used by the Java compiler to remove generic notation and substitute actual type arguments for formal type parameters is called
erasure
In a typical linear list setup:
f you want to show the elements you need to set up a for loop
true or false. the = operator and the == operator perform the same operation
false
true or false: the scope of a variable is limited to the block in which it is defined
false
This is a boolean variable that signals when some condition exists in the program.
flags
Print each key in the dictionary my_dict.
for key in my_dict print(key)
Change all negative values in my_dict to 0.
for key, value in my_dict.items() if value < 0: my_dict[key] = 0
Print twice the value of every value in my_dict.
for v in my_dict.values(): print(2 * v)
Let X be a node in a binary tree. The collection of all descendants of X
form a binary tree called the subtree rooted at X
In a queue when the last_ix (pointing to the last element added to the queue), comes up right behind the first_ix (e.g. last_ix == first_ix-1), this is an indication that the queue is:
full
A sorting algorithm based on a priority queue is
heap sort
A class is generic
if it has type parameters
A recursive computation of the size of a list can work as follows
if the list is empty, return zero; otherwise, recursively compute the size of the tail, add one, and return the result
To add a new element X to a binary search tree:
if the tree is empty, make X the root of a new tree; otherwise, compare X to the root, if X is less, put it in the left subtree, if it is greater, put in the right subtree
what risk does a programmer take when not placing a trailing else at the end of an if-else-if statement
if the user enters something that does not apply to any of the if-else-if statements, the code will simply stop running and produce no output
A list can be considered a recursive data structure because
if you remove the head of the list, what remains is also a list
Binary trees have been used
in compilers and interpreters to represent expressions
An advantage of using generic types is
increased type-safety without the need to do typecasts at run time
A binary tree traversal method that recursively traverses the left subtree, then visits the root, then traverses the right subtree is called
inorder traversal
Comparable
is a class that allows two objects to be compared; WRONG ANSWER
Collections
is a class that contains static methods for working with collections
A priority queue is
is a collection that allows elements to be added, but only allows the minimum element to be removed
data type
is a group of values and the operations defined on those values
Stacks
is a linear collection whose elements are added in a last in, first out (LIFO) manner That is, the last element to be put on a stack is the first one to be removed Think of a stack of books, where you add and remove from the top, but can't reach into the middle
A HashMap
is a subclass of Map that implements the HashCode interface;WRONG ANSWER
Comparable<T> is
is an interface defined in the Java class libraries
midpoint = i + (k - i) / 2 pivot = numbers[midpoint] Determine the midpoint value. numbers = (1, 2, 3, 4, 5), i = 0, k = 4
midpoint = 2. i + ((k-i) / 2). 0 + ((4-0)/2) = 2
A doubly circularly linked list makes it easy to
move forward through a list, and then quickly jump to the beginning of the list when you get to the end
A doubly linked list makes it easy to
move from any node to its successor, and from any node to its predecessor
To remove the first node in a nonempty linked list
move the head reference one node forward: head = head.next;
To remove the first node in a nonempty linked list,
move the head reference one node forward: head = head.next;
A binary tree with no root
must be empty
O ( 100*n^2 + n * log (n) + 34425 n) =
n^2
What is the big-O for this algorithm? for i = 1 to n for j = 1 to 2*n k= 3 00 while k greater than 1 do k = k / 3 // integer division do something.... end end end
n^2
This is an if statement that appears inside another if statement.
nested if statement
The objects that form the units of memory allocation in a linked lists are called
nodes
A linked list class keeps its elements in the order in which they are added, with the index of an element X being greater than the index of any element added to the list before X. Addition of new elements to such a list can be made more efficient
none of the above
This is an empty statement that does nothing.
null statement
Quick-sort is probably not going to be any faster than Selection sort when:
number of elements is small elements are already sorted Correct Answer both of the above
Linked Structures
object references to create links between objects Recall that an object reference variable holds the address of an object A Person object, for instance, could contain a reference to another Person object A series of Person objects would make up a linked list:
Iterators
object that allows the user to acquire and use each element in a collection It works with a collection, but is a separate object An iterator simplifies the classic step of processing elements in a collection
A collision occurs when
objects whose values are not equal have the same hash code
A recursive definition
one which uses the word or concept being defined in the definition itself
Unordered Lists
order is not based on element characteristics The user of the list determines the order of the elements A new element can be put on the front or the rear of the list, or it can be inserted after a particular element already in the list
Ordered Lists
ordered by some inherent characteristic of the elements names in alphabetical order scores in ascending order The elements themselves determine where they are stored in the list
Bubble Sort
orders a list of values by repetitively comparing neighboring elements and swapping their positions if necessary More specifically: scan the list, exchanging adjacent elements if they are not in relative order; this bubbles the highest value to the top scan the list again, bubbling up the second highest value repeat until all elements have been placed in their proper order
Selection Sort
orders a list of values by repetitively putting a particular value into its final position More specifically: find the smallest value in the list switch it with the value in the first position find the next smallest value in the list switch it with the value in the second position repeat until all values are in their proper places
Insertion Sort
orders a values by repetitively inserting a particular value into a sorted subset of the list More specifically: consider the first item to be a sorted sublist of length 1 insert the second item into the sorted sublist, shifting the first item if needed insert the third item into the sorted sublist, shifting the other items as needed repeat until all values have been inserted into their proper positions
Quick Sort
orders values by partitioning the list around one element, then sorting each partition More specifically: choose one element in the list to be the partition element organize the elements so that all elements less than the partition element are to the left and all greater are to the right apply the quick sort algorithm (recursively) to both partitions
Merge Sort
orders values by recursively dividing the list in half until each sub-list has one element, then recombining More specifically: divide the list into two roughly equal parts recursively divide each part in half, continuing until a part contains only one element merge the two parts into one sorted list continue to merge parts as the recursion unfolds
Adding all items from a list to a certain data structure and then removing them one at a time yields a sorted version of the list. The data structure is a
priority queue
Recursion
programming technique in which a method can call itself to fulfill its purpose
A collection that is synchronized
protects data from corruption when the data is accessed by multiple threads
Which of the static data structures we covered employs two indexes:
queue
When you create an instance of a generic class, what types can you pass as arguments for the class type parameters?
reference types only
>, <, and == are
relational operators
One of the advantages of using generics is
that more type problems can be uncovered at compile-time rather than at run time
the following statement should determine whether x is not greater than 20. what is wrong with it: if (!x > 20)
the ! is supposed to be beside the >
the following statement should determine whether count is outside the range of 0to100. what is wrong with it: if(count < 0 && count > 100)
the && means and, and we are looking for the statement to check if the count < 0 OR count > 100
LinkedHashSet differs from HashSet because
the LinkedHashSet allows elements to be retrieved in the same order as they were added
Comparable
specifies a single method, compareTo
In the notation <T extends Number>, the Number class
specifies an upper bound for the parameter type T
Comparator
specifies two methods, compare and equals
A linked list class uses a Node class with successor reference next and field element to store values. A recursive method to print all list elements can be written as
static void printList(Node list) { if (list != null) { System.out.println(list.element); printList(list.next); } }
The code List<String> myLs = new ArrayList<String>( ); uses a List <String> interface variable to reference the concrete ArrayList<String> object. The advantage of doing this is
the class of the collection object can later be changed to LinkedList, or even Vector, without needing to change anything else in the program
An else clause always goes with __________.
the closest previous if clause that doesn't already have its own else clause
When a generic method is called,
the compiler determines the actual types to use for the type parameters from the context
what is wrong with the following code: double value = 12345.678; System.out.printf("%.2d", value)
the d in "%.2d" needs to be an f
This determines whether two different String objects contain the same string.
the equals method
When calculating 5! recursively:
the first multiplication performed is 5*4 the first multiplication performed is 1*2 The last multiplication performed is 5 * 24 Correct Answer both b) and c) is correct
A linked list is represented by a reference to
the first node in the list, unless the list is empty, in which case the reference is set to null
A list method void add(int index, E x) seeking to add an element x that is an object of a class E to a list, should throw an IndexOutOfBoundsException when
the index is negative, or greater than the size of the list
A list method E remove(int index) designed to remove and return the element at the given index should throw IndexOutOfBoundsException when
the index is negative, or is greater than, or equal to, the size of the list
When the pivot element in Quick-sort is placed in its proper position
the pivot is considered sorted all elements to its right are larger than the pivot all the elements to the left are smaller than the pivot Correct! all of the above
Sorting
the process of arranging a group of items into a defined order based on particular criteria
explain the purpose of a flag variable
the purpose of a flag variable is to determine whether to boolean expression is true or false
In order to use recursion on linked lists
the recursive method should be made private, and should be called by a public non-recursive method
When using recursion on linked lists
the recursive method should be made private, and should be called by a public non-recursive method
find the error: if (x==1); y=2; else if (x ==2); y=3; else if (x==3); y=4;
the semicolon after each if/else if statement will cause the following statements to be ignored, and the code will not run
data structure
the set of programming constructs and techniques used to implement a collection
When a generic class with an unconstrained type parameter is instantiated without specifying an actual type argument,
the type Object is used for the unspecified type
the following statement should determine whether count if within the range of 0to100. what is wrong with it: if (count >= 0 || count <= 100)
the || means or, and we are looking for the statement to check if the count is >= 0 AND count <= 100
A LinkedList is the right kind of list to use when
there are lots of insertions and deletions in the middle of the list
find the error: if (num2 == 0) System.out.println("Division by zero is not possible. "); System.out.println("please run the program again"); System.out.println("and enter a number besides zero");
there are no braces
In a binary tree,
there must be at most one node with no predecessor
the conditional operator takes this many operands
three
true or false: a conditionally executed statement should be indented one level from the if clause
true
true or false: all lines in a conditionally executed block should be indented one level
true
true or false: when an if statement is nested in the else clause of another statement, the only time the inner if statement is executed when the boolean expression of the outer if statement is true
true
true or false: when an if statement is nested in the if clause of another statement, the only time the inner if statement is executed is when the boolean expression of the outer if statement is true
true
How do you iterate through a STL vector using iterators
typedef vector <int> :: iterator; Iterator int sum = 0; for (Iterator p = V.begin(): p != V.end(): ++p) sum += *p; return sum;
Logarithmic sorts
typically require nlogv2n comparisons to sort n elements