ITSC 2214 Test 3 Chapters 9-10

¡Supera tus tareas y exámenes ahora con Quizwiz!

quicksort # of comparisons per level:

N = # of items N

merge sort algorithm runtime:

N = # of items O((N)(log(N)))

quicksort # of levels:

N = # of items in a normal scenario: log₂(N) in a worst case scenario: N - 1 <<THE FORMULAS IN THIS QUIZLET THAT USE N SHOULD BE SWAPPED FOR N - 1 WHEN WORST CASE>>

merge sort # of levels:

N = # of items log₂(N)

maximum N-node binary tree height is:

N = # of nodes N - 1

minimum N-node binary tree height is:

N = # of nodes h = log₂(N)

The height of a binary search tree is given as h. What is the maximum number of nodes in the tree?

(2^(h+1)) - 1

How many elements will the temporary merge list have for merging two partitions with 250 elements each?

500

If a balanced binary search tree has a height of 5, how many comparisons will need to be done at most to determine if a target item is in the tree?

6

How many times is countDown() called if main() calls CountDown(5)?

6 The first call countDown(5) comes from main(). Then countDown() calls itself with 4, then with 3, 2, 1, and finally 0. That last instance does not call again, but instead returns.

Before writing a recursive method, a programmer should determine:

1.) Does the problem naturally have a recursive solution? 2.) Is a recursive solution better than a non-recursive solution?

You have the following types of coins: 1, 5, 10, 25, 70, 100. You would like to make change of 140 cents. What is the solution (set of coins) of the greedy algorithm?

100 + 25 + 10 + 5

You have the following array: {12, 9, 27, 8, -4, 28, 40, 33} You have done one iteration of quicksort. Which element(s) might have been the pivot?

12 28

In a perfect binary tree, every internal node has exactly two children. If there are 128 leaf nodes in the tree, how many internal nodes are there in the tree?

127

If a sorted list has elements 0 to 50 and the item being searched for is at element 6, how many times will findMatch() be called?

3 > First call: findMatch(0, 50), which checks element (0 + 50) / 2 = 25 > Second call: findMatch(0, 25), which checks element 12 (0 + 25) / 2 = 12 (the fraction is truncated) > Third call: findMatch(0, 12), which checks element 6 and finds the element

The number of nodes in a perfect binary tree of height of 4 is:

31

Use the following recursive method: public int mysteryMethod(int n) { if (n < 0) { return 5; } else { return mysteryMethod(n-1) + mysteryMethod(n-2); } } What value will be returned from the call mysteryMethod(3)?

40

In a perfect binary search tree, every internal node has exactly two children. If there are 64 leaf nodes in the tree, how many internal nodes are there in the tree? Count the root as an internal node.

63

If an alphabetically ascending list has elements 0 to 50, and the item at element 0 is "Bananas", how many recursive calls to findMatch() will be made during the failed search for "Apples"?

7 > First call: findMatch(0, 50) > Subsequent calls will pass these (lowVal, highVal) value pairs: (0, 25), (0, 12), (0, 6), (0, 3), (0, 1), (0, 0). At (0, 1) the midVal is 0 because Apples is less than the item at element 0 (Bananas) > The next call is findMatch(0, 0) > Because the rangeSize is now 1, the second base case is reached and the method returns -1

Here is an array which has just been partitioned by the first step of quicksort: 3, 0, 2, 1, 7, 15, 11, 20, 13 Which of these elements was the pivot?

7, because it is the first pivot on the left?

Find all the possible pivots in the list of items below, assuming this list has been through one sorting iteration: 889 356 471 210 995 1700 1312 1001 999 2087

995 2087

Which of the following are true about merge sort?

> A temporary array that is the same size as the original array is required for a mergesort > The worst-case time complexity for merge sort is O(n log (n))

Remove an internal node with two children

> First, the algorithm locates X's successor (the leftmost child of X's right subtree), and copies the successor to X. > Then, the algorithm recursively removes the successor from the right subtree.

Remove an internal node with single child

> If X has a parent (so X is not the root), the parent's left or right child (whichever points to X) is assigned with X's single child. > Else, if X was the root, the root pointer is assigned with X's single child.

Remove a leaf node

> If X has a parent (so X is not the root), the parent's left or right child (whichever points to X) is assigned with null. > Else, if X was the root, the root pointer is assigned with null, and the BST is now empty.

if-else recursive pattern:

> The recursive method has an if-else statement > The if branch ends the recursion, known as the base case > The else branch has recursive calls > Such an if-else pattern is common in recursive methods

If you are conducting a binary search through a tree that holds Student objects, and you are trying to find out whether a student with a certain ID exists in the data set, what must be true in order for this search to be able to be performed in O(log n) time?

> The tree must be balanced. > The tree must be a binary search tree (ie. data stored in order) > The Student class must implement the Comparable interface, using ID as the field for sorting students.

Creating a recursive method can be accomplished in two steps.

> Write the base case > Write the recursive case

Which statements are true about quicksort?

> You have to be consistent in what you choose as the pivot for each iteration. > After a partition, the items on the left of the pivot are less than or equal to the pivot.

A remove from a max-heap

> a removal of the root, and is done by replacing the root with the last level's right node, and swapping that node with its greatest child until no max-heap property violation occurs > Because upon completion that node will occupy another node's location (which was swapped upwards), the tree height remains the minimum possible

simple BST search algorithm

> checks the current node (initially the tree's root) returning that node immediately as a match > else assigning the current node with the left (if key is less) or right (if key is greater) child and repeating > If such a child is null, the algorithm returns null after exiting the loop (matching node not found)

Given a new node, a BST insert operation:

> inserts the new node in a proper location obeying the BST ordering property > A simple BST insert algorithm compares the new node with the current node (initially the root)

heapify

> operation that is used to turn an array into a heap > starts on the internal node with the largest index and continues down to, and including, the root node at index 0. Given a binary tree with N nodes, the largest internal node index is floor(N / 2) - 1 > Since leaf nodes already satisfy the max heap property, heapifying to build a max-heap is achieved by percolating down on every non-leaf node in reverse order.

Given a key, a BST remove operation:

> removes the first-found matching node, restructuring the tree to preserve the BST ordering property > The algorithm first searches for a matching node just like the search algorithm > If found (call this node X), the algorithm performs one of the sub-algorithms

An insert into a max-heap:

> starts by inserting the node in the tree's last level, and then swapping the node with its parent until no max-heap property violation occurs > Inserts fill a level (left-to-right) before adding another level, so the tree's height is always the minimum possible

height

> the largest depth of any node. > A tree with just one node has height 0 > the maximum edges from the root to any leaf

Given a tree representation of a heap, the heap's array form is produced by:

> traversing the tree's levels from left to right and top to bottom > The root node is always the entry at index 0 in the array, the root's left child is the entry at index 1, the root's right child is the entry at index 2, and so on

Your friend, Levi the Restaurant Manager, wants to create a hierarchy system that will keep track of all the chefs in his kitchen. If the top chef is sick, he needs to know who should be put in charge of the kitchen, and if that person also bails, who is the next person who should be put in charge? What is the best data structure you should use to design this for him?

A max heap

recursive method

A method that calls itself

Parent

A node with a child is said to be that child's parent

Internal node

A node with at least one child

Leaf

A tree node with no children

balanced

A tree whose: 1.) Left and right subtrees' heights differ by at most one 2.) Left subtree is balanced 3.) Right subtree is balanced

level

All nodes with the same depth

When you add to a heap, you first put the new element:

At the bottom left-most open slot

Write the base case:

Every recursive method must have a case that returns a value without performing a recursive call. That case is called the base case. A programmer may write that part of the method first, and then test. There may be multiple base cases.

A heap can become unbalanced if the same number is added repeatedly. (T/F)

False

The depth of a node X is the number of nodes in the path from the root to node X, including the root and the specified node. (T/F)

False

With MergeSort, the larger the array is to be sorted, the more complicated the recursive algorithm gets.

False

An array sorted in ascending order is already a valid max-heap (T/F)

False > A max-heap can be used to sort an array, but a sorted array may not be valid max-heap. Ex: The array with values 10, 20, and 30 would have a root node with 2 larger children, and would not be a valid max-heap. > ascending means ascending as you go from top to bottom, so smallest number at the top, so not max-heap

Calling Heapsort on an array with 1 element will cause an out of bounds array access. (T/F)

False > In the first loop, i is initialized with 0 and MaxHeapPercolateDown is called on the root, which has no effect. In the second loop, i is initialized with 0 and the loop body never executes.

The formula for computing child node indices does not work on the root node. (T/F)

False > The formulas 2 * i + 1 and 2 * i + 2 work correctly to compute child indices of 1 and 2 for the root node.

Heapsort uses recursion (T/F)

False > The only function Heapsort calls is MaxHeapPercolateDown, which is not recursive. So, the Heapsort algorithm is not recursive.

Driving to the store: Go 1 mile. Turn left on Main Street. Go 1/2 mile. Recursive? (T/F)

False > There is no recursive call to "driving to the store".

Parent and child indices for a heap:

For Index ( i ): Parent Index = floor((i - 1) / 2) Child Indices = (2 * i + 1), (2 * i + 2)

Searching a BST in the worst case requires has an ___ complexity

H = tree height O(H)

What is the output of the following code: public static void fun(int x){ System.out.print("Hi "); x=x-1; if(x!=0) fun(x); System.out.print("Bye "); } public static void main(String[] args) { fun(5); }

Hi Hi Hi Hi Hi Bye Bye Bye Bye Bye

Search for insert location:

If the left (or right) child is not null, the algorithm assigns the current node with that child and continues searching for a proper insert location

Insert as right child:

If the new node's key is greater than the current node, and the current node's right child is null, the algorithm assigns the node's right child with the new node

Insert as left child:

If the new node's key is less than the current node, and the current node's left child is null, the algorithm assigns that node's left child with the new node

Which type of traversal of binary search tree outputs the value in sorted order?

In-Order

The divide and conquer algorithm breaks down the given problem recursively into simpler sub-problems, then puts together the solutions to these sub-problems. If your neighbor Leyna wants to sort a list of integers from largest to smallest using the divide and conquer approach, she will first break down the list into 2 lists and break it down further if necessary. After she sorts each list, she will combine the sorted sublists to generate the final result. Which sorting algorithm does this resemble?

Merge Sort

merge sort # of comparisons:

N = # of items (N)(log(N))

quicksort # of comparisons:

N = # of items > normally: (N)(log₂(N)) > worst case: (N)(N - 1)

quicksort algorithm runtime:

N = # of items > normally: O((N)(log(N))) > worst case: O(N²)

Heapsort's worst-case runtime is ___

O(N log N)

MaxHeapPercolateDown's worst-case runtime is:

O(log N)

If a binary search tree is balanced, what is the Big O complexity of search?

O(log n)

The worst-case cost of removing an item from a heap is:

O(log n)

Given a max-heap with N nodes, what is the complexity for removing the root?

O(log(N))

Given a max-heap with N nodes, what is the complexity of an insert, assuming an insert is dominated by the swaps?

O(log(N))

Removing a node from an N-node nearly-full BST has what computational complexity?

O(logN) > The computation is dominated by searching for the node, which is O(logN). > The actual removal is just a few pointer updates.

Running merge sort on an array of size n which is already sorted is:

O(n log n)

If a binary search tree is not balanced (unbalanced), what is the Big O complexity of an add operation?

O(n)

What is the worst case time complexity for inserting an element into a binary search tree? Do not assume it is balanced, or that you have to do any rebalancing.

O(n)

In a recursive method, there is often a temp variable to store intermediate results. How many copies of this variable will exist from the time a recursive method is first called until it finally finishes?

One for every version of the recursive method that gets put on the call stack.

Traversing a binary tree by going to the left and right subtrees and then the root is called _______traversal.

Postorder

A list has 5 elements numbered 0 to 4, with these letter values: 0: A, 1: B, 2: D, 3: E, 4: F. In searching for item C, findMatch(0, 2) is called. What happens next?

Recursive call: findMarch(2, 2) > findMatch(0, 2) checks list[1]. C > B so the search proceeds to the right, so findMatch(1 + 1, 2) or findMatch(2, 2) > That call will return -1 (no match).

Which statement accurately describes a max-heap?

The heap is only sorted in the sense that each node's parent has a larger value than itself, but otherwise not sorted

edge

The link from a node to a child

Root

The one tree node with no parent (the "top" node)

Write the recursive case:

The programmer then adds the recursive case to the method.

The following method returns what? public String mystery(String s) { if (s.size() <= 0) return s; char c = s.charAt(0); String subString = s.subString(1); String returnVal = mystery(subString) + c; return returnVal; }

The reverse string.

percolating

The upward movement of a node in a max-heap

In a tree, if we have N nodes then:

There are N-1 edges

A recursive method can have two base cases, such as N == 0 returning 0, and N == 1 returning 1. (T/F)

True

In a heap, it is possible for the left child of a node to be greater than the right child (T/F)

True

Helping N people: If N is 1, help that person. Else, help the first N/2 people, then help the second N/2 people. Recursive? (T/F)

True > Base case is to help 1 person. Recursive applications are to help the first N/2, then the second N/2.

The formula for computing parent node index does not work on the root node. (T/F)

True > Since the root node has no parent, the formula must not be used on the root node. The formula holds for all other nodes in the heap.

Heap implementations must check to see if a node is a leaf node before using the child index formula. (T/F)

True > The formula always gives appropriate child indices, but the check to see if such children actually exist in the heap must be done before utilizing the formula.

post order traversal

Until all nodes are traversed: Step 1 − Recursively traverse left subtree. Step 2 − Recursively traverse right subtree. Step 3 − Visit root node. > when another tree is encountered, the algorithm is restarted for that tree until another tree is encountered or it ends, after it hits the end, it goes back up the chain and completes any traversals it hasn't done yet, this is all based on recursion

in-order traversal

Until all nodes are traversed: Step 1 − Recursively traverse left subtree. Step 2 − Visit root node. Step 3 − Recursively traverse right subtree. > when another tree is encountered, the algorithm is restarted for that tree until another tree is encountered or it ends, after it hits the end, it goes back up the chain and completes any traversals it hasn't done yet, this is all based on recursion > visits all nodes in a BST from smallest to largest

pre-order traversal

Until all nodes are traversed: Step 1 − Visit root node. Step 2 − Recursively traverse left subtree. Step 3 − Recursively traverse right subtree. > when another tree is encountered, the algorithm is restarted for that tree until another tree is encountered or it ends, after it hits the end, it goes back up the chain and completes any traversals it hasn't done yet, this is all based on recursion

max-heap

a binary tree that maintains the simple property that a node's key is greater than or equal to the node's childrens' keys > results in a node's key being greater than or equal to all the node's descendants' keys > Therefore, a max-heap's root always has the maximum key in the entire tree

algorithm

a sequence of steps for solving a problem

Quicksort

a sorting algorithm that picks a pivot, typically the middle element, and sorts the input into two parts, one containing elements higher than the pivot, and one containing elements less than or equal to the pivot 1.) the low part starts from the left and iterates right (l) until it finds a value higher than the pivot, then it stops 2.) the high part starts from the right and iterates left (h) until it finds an item less than the pivot, then it stops 3.) the two found items are swapped, and each iterating index is moved one closer to each other and the process repeats from where it left off 4.) the process stops when the two iterating indexes both find items, and their indexes either meet at the same value or go past each other 6.) the iterating index that started on the right (h) is returned because it's the index of the last element contained in the low partition 5.) Quicksort is then called on the high and low partitions and repeated until you have a set of parts with one number each and the parts are combined in the order they are now sorted to form a sorted set > the iterating indexes are never reset or pushed away from each other they only go towards each other > the high and low parts are not sorted in any particular order

Heapsort

a sorting algorithm that takes advantage of a max-heap's properties by repeatedly removing the max and building a sorted array in reverse order. An array of unsorted values must first be converted into a heap using heapify > max is swapped with the last element in the array and the new last element in the array which holds the max is removed, then the swapped last value at the root is percolated down the array, and the process repeats until the array is empty

Merge sort

a sorting algorithm which splits a list in half until each item is alone, then merges them back together in the correct order to get a sorted list 1.) splits the list in half until each item is alone, with the middle element of each level being included in the first partition 2.) for each level, make the first items of each partition index 0 3.) transfer the smallest item and put it into the merged partition, and adjust indexes so the next element in that partition is index 0 4.) repeat step 3 until one of the partitions reaches an end, then if there are still elements remaining, transfer the remaining items to the new partition in order 5.) repeat steps 2-4 for each level until there is only one partition

Which algorithm below describes the process of adding a node to a binary search tree (assume we aren't concerned about rebalancing)?

add(value, root) { If root is null, put value as item at root. else, if value is less than value of root { add(value, leftChild) } else add(value, rightChild) }

tree traversal

algorithm which visits all nodes in the tree once and performs an operation on each node

pivot

any value within the array being sorted, commonly the value of the middle array element

If you need to be able to efficiently find and remove any item, you should use a:

binary search tree

binary tree

each node has up to two children, known as a left child and a right child. "Binary" means two, referring to the two children

full

every node contains 0 or 2 children

the pivot after the first iteration:

everything to the left must be smaller and everything to the right must be larger

To search nodes means to:

find a node with a desired key, if such a node exists. A BST may yield faster searches than a list. Searching a BST starts by visiting the root node

Max-heap largest internal node index:

for N nodes in binary heap: Largest internal node index: floor(N / 2) - 1

binary search tree

has an ordering property that any node's left subtree keys ≤ the node's key, and the right subtree's keys > the node's key

perfect

if all internal nodes have 2 children and all leaf nodes are at the same level

complete

if all levels, except the last level, are completely full and all nodes in the last level are on the left

ancestors

include the node's parent, the parent's parent, etc., up to the tree's root

What line of code is needed below to complete the factorial recursion method? (Recall that a factorial n! is equal to n*(n-1)*(n-2)*(n-3)....*1) public int fact(int x) { if (x == 1) return 1; // what line goes here? return result; }

int result = x * fact(x-1);

When solving a problem recursively, the base case ___

is where the problem is solved directly.

BST ordering

its just numeric or lexicographic order

Given N nodes, what is the height of a max-heap?

log(N)

searching a BST takes ___ comparisons

log₂(N) + 1

Assume you are going to run an array of n elements through mergesort. Assume n is an even power of 2. How many partitions will be created, including the first partition (which is the whole array)?

n-1

Given a key, a search algorithm:

returns the first node found matching that key, or returns null if a matching node is not found

min-heap

similar to a max-heap, but a node's key is less than or equal to its children's keys

recursive algorithm

solves a problem by breaking that problem into smaller subproblems, solving these subproblems, and combining the solutions

Fibonacci sequence

starting with 0, 1, the pattern is to compute the next number by adding the previous two numbers. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, etc.

# of percolate-down operations:

take the largest internal node index and add all the index values below it, excluding the index itself and including 0

greatest common divisor

the largest number that divides evenly into two numbers, e.g. GCD(12, 8) = 4. One GCD algorithm (described by Euclid around 300 BC) subtracts the smaller number from the larger number until both numbers are equal. > Ex: GCD(12, 8): Subtract 8 from 12, yielding 4. GCD(4, 8): Subtract 4 from 8, yielding 4. GCD(4, 4): Numbers are equal, return 4 > The base case is that the two numbers are equal, so that number is returned. The recursive case subtracts the smaller number from the larger number and then calls GCD with the new pair of numbers

successor

the node that comes after in the BST ordering

predecessor

the node that comes before in the BST ordering

depth

the number of edges on the path from the root to the node. The root node thus has depth 0

base case

the thing the recursive algorithm split up in order to do, aka the goal of the algorithm

Heaps are typically stored:

using arrays

the following array for a minHeap, what would the array look like after adding 9 to the heap? {8, 10, 60, 15, 12, 75, 61}

{8, 9, 60, 10, 12, 75, 61, 15}


Conjuntos de estudio relacionados

Chapter 6: Organizing: Groups and Teams

View Set

BIO Exam #3 multiple choice quiz

View Set

Exceptions to the Warrant Requirement

View Set

Основи наукового пізнання

View Set