APCS: Unit 8
Recursion problem: Trace fact(5) public static int fact(int num) { if (num == 0) return 1; else return num * fact(num - 1); }
**watch recursion video if you don't understand
Iterative problem: Trace fact(4) public static int fact(int num) { int tmp = 1; for (int i = 1; i <= num; i++) { tmp *= i; } return tmp; }
**watch video/go over notes if you don't understand
Algorithm
- An abstract and formal step-by-step recipe that describes how to perform a certain task or solve a certain problem. -They are general, abstract and compact
Binary search:
-A binary search locates a value in a sorted (ascending or descending order)array by: --Determining whether the value occurs in the first or second half --Then repeating the search in one of the halves --Elements cannot be repeated; no duplicate values in the array -The size of the search is cut in half with each step. -A "divide and conquer" algorithm. -Works very fast: only 20 comparisons are needed for an array of 1,000,000 elements; (30 comparisons can handle 1,000,000,000 elements; etc.). -Can be coded recursively or non-recursively -Non-recursive requires less memory and fewer steps. -We say that this is an O(log n) algorithm.
Explain what recursive methods are, and give an example of the code:
-A recursive method calls itself -Must have a base case (can be implicit) -Example: Trace addSquares(4) -Reference the notes resource that has this example traced in detail public class MyMath { public static int addSquares (int n) { if (n == 0) // if n is equal to 0 return 0; else return addSquares (n - 1) + n * n; } }
Binary examples:
-An array of 3 elements requires at most 2 comparisons -An array of 7 elements requires at most 3 comparisons -An array of 15 elements requires at most 4 comparisons -An array of 2n - 1 or fewer requires at most n comparisons -Log2n tells you roughly the number of operations
What are some important steps when tracing recursion?
-As always, go line by line --Recursive methods may have many copies -Every method call creates a new copy and transfers flow of control to the new copy -Each copy has its own: --code --parameters --local variables -After completing a recursive call: --Control goes back to the calling environment --Recursive call must execute completely before control goes back to previous call --Execution in previous call begins from point immediately following recursive call
Big O notation:
-Big O notation is used in Computer Science to describe the performance or complexity of an algorithm. -Big O specifically describes the worst-case scenario, and can be used to describe the execution time required by an algorithm. -O(N) describes an algorithm whose performance will grow linearly and in direct proportion to the size of the input data set. This will be sequential search. -O(log N) produces a growth curve that peaks at the beginning and slowly flattens out as the size of the data sets increase. This will be binary search.
How does recursion work?
-Implemented on a computer as a form of iterations, but hidden from the programmer -Assisted by the system stack -Recursion is especially useful for dealing with nested structures or branching processes -It is implemented by means of functions calling themselves
Insertion sort
-Insertion sort is the method that many people use to sort playing cards. Pick up one card at a time and insert it so that the cards stay sorted. -Insertion Sort is good when the array is almost sorted with only a few elements out of place.
What is the relationship between the base case and recursion?
-Must have a base case when the task is so simple that no recursion is needed. -Recursive calls must eventually converge to a base case. -Stops the recursion (prevents infinite loops) -Solved directly to return a value without calling the same method again
What is the quicksort algorithm?
-No temporary arrays are required. 1. Divide and conquer Partition the range 2. Sort each partition -In quicksort, one partitions the elements into two groups, holding the smaller and larger elements. Then one sorts each group. -Quicksort is one of the most popular sorting algorithms -This can be explained by the fact that on average, Quicksort is one of the fastest known sorting algorithms.
What are some facts about recursion?
-Recursive methods call themselves -Each call solves an identical problem --The code is the same! --Successive calls solve smaller/simpler instances -Every recursive algorithm has at least one base case --A known/easy to solve case --Often, when we reach 1 or 0
What do iterations do?
-Repeat the same sequence of instructions multiple times -Start with initial values of variables -Values of some of the variables change in each cycle -Stop when the tested condition becomes false
Sequential search:
-Scans the list comparing the target value to each element. -Examines all values in an array until it finds a match or reaches the end -The average number of comparisons (assuming the target value is equal to one of the elements of the array, randomly chosen) is about n / 2 (where n = arr.length). -The maximum visits : n comparisons. -Also n comparisons are needed to establish that the target value is not in the array. -A linear search locates a value in an array in O(n) steps.
Selection sort
-Selection sort is a well-known algorithm that makes many passes over an input array to put its elements into sorted order. -Each time it runs through a loop, it selects the smallest value and puts it in the proper place near the front of the array.
What is the difference between merge sort and selection sort?
-Selection sort is an O(n2) algorithm. -Merge sort is an O(n log(n)) algorithm. -The n log(n) function grows much more slowly than n2.
Sequential vs. Binary:
-Should we sort an array before searching? --Linear search - O(n) --Binary search - O(n log(n)) -If you search the array only once --Linear search is more efficient (on small or unordered lists) -Binary is the fastest if the list is already sorted -If you will make many searches --Worthwhile to sort and use binary search
Merge sort:
-Sorts an array by --Cutting the array in half --Recursively sorting each half --Merging the sorted halves -Dramatically faster than the selection sort -In merge sort, you sort each half, then merges the sorted halves. -Disadvantage: having to create a temporary array which takes up memory.
Insertion sort and Big O:
-The average number of comparisons is roughly half of the number in Selection Sort. -The best case is when the array is already sorted: takes only (n-1) comparisons. -The worst case is n(n-1) / 2 when the array is sorted in reverse order. -On average, an O(n2) algorithm.
Selection sort and Big O:
-The total number of comparisons is always (n-1) + (n-2) + ... + 1 = n(n-1) / 2 -No average, best, or worst case — always the same. -An O(n2) algorithm. -In selection sort, pick the smallest element and swap it with the first one. Pick the smallest element of the remaining ones and swap it with the next one, and so on. -Slow when run on large data sets.
Sorting:
-To sort means to rearrange the elements of a list in ascending or descending order. -Examples of sorting applications: --a directory of files sorted by name or date --bank checks sorted by account # --addresses in a mailing list sorted by zip code --hits found by a search engine sorted by relevance --credit card transactions sorted by date
An array contains 3, 6, 4, 1, 5, 2, in that order. Selection Sort is used to sort it in ascending order. What is the order of elements after the first three passes (through the outer loop)?
1 2 3 4 5 6 (3rd pass)
What are the steps that occur when doing merge sort?
1) split the array into two halves (you can use midpoint) 2) sort the left half (from 0 to half the length) 3) sort the right half (from half the length to the full length) 4) merge the two halves
What is the sequence of values in b after the following code is executed? int[] b = {1, 2, 3, 4, 5}; for (int i = 0; i < b.length; i++) { int j = b.length - 1 - i; int temp = b[i]; b[i] = b[j]; b[j] = temp; }
1, 2, 3, 4, 5
What are the steps that occur when selection sorting?
1. Find the smallest and swap it with the first element 2. Find the next smallest. It is already in the correct place 3. Find the next smallest and swap it with first element of unsorted portion 4. Repeat 5. When the unsorted portion is of length 1, we are done
What are the steps that occur when doing quicksort?
1. Pick one element, called "pivot" (typically the middle but it doesn't have to be) 2. Partition the array, so that all the elements to the left of pivot are ≤ pivot; all the elements to the right of pivot are ≥ pivot. 3. Sort recursively the left and the right segments using... Quicksort.
What are the steps that occur when doing insertion sort?
1. k = 1; keep the first k elements in order. 2. Take the (k+1)-th element and insert among the first k in the right place. 3. Increment k by 1; repeat from Step 2 (while k < n)
Trace sorting {12, 7, 1, -10, 3 ,7, 9, 5} using insertion sort. (show all steps)
12 7 1 -10 3 7 9 5 7 12 1 -10 3 7 9 5 1 7 12 -10 3 7 9 5 -10 1 7 12 3 7 9 5 -10 1 3 7 12 7 9 5 -10 1 3 7 7 12 9 5 -10 1 3 7 7 9 12 5 -10 1 3 5 7 7 9 12
Consider the following method: public void mystery(int n) { if (n <= 1) { System.out.print(n); } else { System.out.print("*"); mystery((n-1) / 2); } } For which input n does mystery(n) give the output ***1?
15
Given int[] list = {5, 1, 6, 4, 2, 7, 3}, what are the contents of list after the partitioning phase of Quicksort if the middle element is chosen as the pivot?
3, 1, 2, 4, 6, 7, 5
Consider the following method: public int someFun(int n) { if (n <= 0) return 2; else return someFun(n-1)*someFun(n-1); } When the program calls someFun(5), how many times will someFun(3) be called?
4
Trace this recursion for addSquares(5). What is the output? public class MyMath { public static int addSquares (int n) { if (n == 0) // if n is equal to 0 return 0; else return addSquares(n - 1) + n * n; } }
55
Consider the following code snippet: public static void sort(int[] a) { for (int i = 1; i < a.length; i++) { int next = a[i]; int j = i; while (j > 0 && a[j - 1] > next) { a[j] = a[j - 1]; j--; } a[j] = next; } } What sort algorithm is used in this code? a) insertion sort b) selection sort c) merge sort d) quicksort
A
Consider the minimumPosition method from the SelectionSorter class. Complete the code to write a maximumPosition method that returns the index of the largest element in the range from index from to the end of the array. private static int minimumPosition(int[] a, int from) { int minPos = from; for (int i = from + 1; i < a.length; i++) { if (a[i] < a[minPos]) { minPos = i; } } return minPos; } private static int maximumPosition(int[] a, int from) { int maxPos = from; for (int i = from + 1; i < a.length; i++) { ________________ } return maxPos; } a) if(a[i] > a[maxPos]) { maxPos = i; } b) if(a[i] == a[maxPos]) { maxPos = i; } c) if(a[i] < a[maxPos]) { maxPos = i; } d) if(a[i] <= a[maxPos]) { maxPos = i; }
A
If an element is present in an array of length n, how many element visits, on average, are necessary to find it using a linear search? a) n / 2 b) n c) 2n d) n2
A
If the array is already sorted, what is the performance of insertion sort? a) O(n) b) O(n2) c) O(log n) d) O(n log n)
A
If you implement a recursive linear search, its performance will be ____. a) O(n) b) O(n2) c) O(log (n)) d) O(n log (n))
A
In Big-Oh notation, selection sort is a(n) ____ algorithm. a) O(n2) b) O(1) c) log n d) O(log n2)
A
The largestPosition method below returns the index of the largest element in the tail range of an array of integers. Select the expression that would be needed to complete the selectionSort method below, so that it sorts the elements in descending order. /** Finds the largest element in the tail range of an array. @param a the array to be searched @param from the first position in a to compare @return the position of the largest element in range a[from]..a[a.length - 1] */ private static int largestPosition(int[] a, int from) { int maxPos = from; for (int j = from + 1; j < a.length; j++) { if (a[j] > a[maxPos]) { maxPos = j; } } return maxPos; } public static void selectionSort(int[] a) { for ____________________________________ { int maxPos = largestPosition(a, i); ArrayUtil.swap(a, maxPos, i); } } a) (int i = 0; i < a.length - 1; i++) b) (int i = 0; i < a.length; i++) c) (int i = a.length; i > 0; i--) d) (int i = a.length - 1; i > 0; i--)
A
What type of algorithm places elements in order? a) sorting b) searching c) insertion d) deletion
A
Which sort algorithm starts with an initial sequence of size 1, which is assumed to be sorted, and increases the size of the sorted sequence in the array in each iteration? a) insertion sort b) selection sort c) merge sort d) quicksort
A
Pseudocode
A sequence of statements, more precise notation
A search technique where, in each step, you split the size of the search in half is called a____ search. a) random b) binary c) linear d) merging
B
After one iteration of selection sort working on an array of 10 elements, what must hold true? a) The array cannot be sorted. b) One element must be correctly placed. c) At least two elements are correctly placed. d) The largest element is correctly placed.
B
Assume we are using quicksort to sort an array in ascending order. What can we conclude about the elements to the left of the currently placed pivot element? a) They are all sorted. b) They are all less than or equal to the pivot element. c) They are all greater than or equal to the pivot element. d) None can equal the pivot element.
B
Can you search the following array using binary search? int[] A = {6, 5, 4, 2, 0, 1, -1, -17}; a) Yes. Binary search can be applied to any array. b) No. Binary search can be applied to a sorted array only. c) Yes, but the algorithm runs slower because the array is in descending order. d) No, negative numbers are not allowed because they indicate that a value is not present.
B
Consider the sort method shown below for selection sort: public static void sort(int[] a) { for (int i = 0; i < a.length - 1; i++) { int minPos = minimumPosition(i); swap(minPos, i); } } Suppose we modify the loop condition to read i < a.length. What would be the result? a) An exception would occur. b) The sort would work, but run one more iteration. c) The sort would work but with one less iteration. d) The sort would work exactly the same as before the code modification.
B
In each iteration, selection sort places which element in the correct location? a) The smallest in the array. b) The smallest element not yet placed in prior iterations. c) The largest element in the array. d) A random element.
B
Merge sort is a(n) ____ algorithm. a) O(n) b) O(n log(n)) c) O(n2) d) O(log n)
B
Suppose it takes about 18 milliseconds to sort an array of 80,000 random numbers using Mergesort. Suppose for an array of 160,000 numbers, Mergesort runs for 40 milliseconds. Approximately how much time will Mergesort run on an array of 320,000 numbers? Chose the closest estimate. A) 80 milliseconds B) 88 milliseconds C) 96 milliseconds D) 126 milliseconds E) 160 milliseconds (For 160,000 it takes 18ms to sort each half. Then merging together the two sorted halves with 80,000 numbers in each of them takes 40-2*18 = 4 ms. For 320,000 elements, it will take 2*40 to sort each half and 2*4 to merge the sorted halves with 160,000 numbers in each, for the total of 2*40+8 = 88 ms.)
B
The code segment below is designed to add the elements in an array of integers. Select the expression needed to complete the code segment so that it calculates the running time elapsed. long start = System.currentTimeMillis(); int sum = 0; for (int k = 0; k < values.length; k++) { sum = sum + values[k]; } long runningTime = ____________________________; a) System.currentTimeMillis() b) System.currentTimeMillis() - start c) System.currentTimeMillis() + start d) runningTime + start - System.currentTimeMillis()
B
The code segment below prints some of the elements in an array with size n. Select an expression to complete the code segment so that the resulting algorithm has O(log n) running time. for __________________________ { System.out.println(array[j]); } a) (int j = 0; j < array.length; j = j + 2) b) (int j = 1; j < array.length; j = j * 2) c) (int j = 0; j < array.length / 2; j++) d) (int j = 0; j < array.length; j++)
B
Binary search is an ____ algorithm. a) O(n) b) O(n2) c) O(log n) d) O(n log n)
C
Given the following code snippet for searching an array: int[] arr = {23, 25, 29, 34, 42}; int newVal = 15; int pos = Arrays.binarySearch(arr, newVal); What value will pos have when this code is executed? a) 0 b) 1 c) -1 d) -2
C
The following code is an example of a ___ search. public static int search(int[] a, int v) { for (int i = 0; i < a.length; i++) { if (a[i] == v) { return i; } } return -1; } a) sorted b) binary c) linear d) random
C
The merge sort algorithm presented in section 14.4, which sorts an array of integers in ascending order, uses the merge method which is partially shown below. Select the condition that would be needed to complete the method so that the elements are sorted in descending order. private static void merge(int[] first, int[] second, int[] a) { int iFirst = 0; int iSecond = 0; int j = 0; while (iFirst < first.length && iSecond < second.length) { if (_____________________________) { a[j] = first[iFirst]; iFirst++; } else { a[j] = second[iSecond]; iSecond++; } j++; } // rest of the method follows here } a) first[iFirst] < second[iSecond] b) iFirst < iSecond c) first[iFirst] > second[iSecond] d) iFirst > iSecond
C
The partial linear search method below is designed to search an array of String objects. Select the expression that would be needed to complete the method. public static int search(String[] a, String item) { for (int i = 0; i < a.length; i++) { if ( ____________________________ ) { return i; } return -1; } } a) a[i] == item b) a[i].compareTo(item) c) a[i].equals(item) d) a[i].indexOf(item)
C
Which of the sorts in the textbook can be characterized by the fact that the best case will have a running time of θ(n) if the data is already sorted? I quicksort II selection sort III insertion sort a) I b) II c) III d) I and III
C
Which sort algorithm starts by cutting the array in half and then recursively sorts each half? a) insertion sort b) selection sort c) merge sort d) quicksort
C
A binary search is generally ____ a linear search. a) slower than b) equal to c) less efficient than d) faster than
D
Assume we are using quicksort to sort an array in ascending order. Into which array location does quicksort's strategy place a pivot element after partitioning? a) lowest index in array still available b) highest index in array still available c) closer to its correct final location d) its final correct location
D
Consider the sort method shown below for selection sort: public static void sort (int[] a) { for (int i = 0; i < a.length - 1; i++) { int minPos = minimumPosition(i); swap(minPos, i); } } Suppose we modify the call to the swap method call to read swap(i, minPos). What would be the result? a) An exception would occur. b) The sort would produce incorrect results. c) The sort would work, but sort backwards. d) The sort would produce correct results.
D
In big-Oh notation, suppose an algorithm requires an order of n3 element visits. How does doubling the number of elements affect the number of visits? a) It doubles the number of visits. b) It quadruples the number of visits. c) It triples the number of visits. d) It number of visits goes up by a factor of eight.
D
The code segment below displays a pattern of asterisks. Select an expression to complete the code segment so that the resulting algorithm has O(n) running time. for (int k = 0; k < n; k++) { for _______________________ { System.out.print("*"); } System.out.println(); } a) (int j = n; j > 0; j = j / 2) b) (int j = n; j > 0; j--) c) (int j = 1; j < k; j++) d) (int j = 1; j <= 10; j++)
D
The partial binary search method below is designed to search an array of String objects sorted in ascending order. Select the expression that would be needed to complete the method. public static int search(String[] a, int low, int high, String item) { if (low <= high) { int mid = (low + high) / 2; int result = ____________________________; if (result == 0) { return mid; } else if (result < 0) { return search(a, mid + 1, high, item); } else { return search(a, low, mid - 1, item); } } return -1; } a) a[low].compareTo(item) b) item.equals(a[mid]) c) item.compareTo(a[mid]) d) a[mid].compareTo(item)
D
Which of the following best describes the base case(s) in the following recursive method? public int factorial(int n) { int product = 1; if (n > 1) product = n * factorial(n-1); return product; } A) The method does not have a base case B) n > 0 C) n > 1 D) n ≤ 1
D
Which of the following features indicates that a method is recursive? A) It includes at least one for statement B) It isolates the case when its parameter is equal to 1 and deals with it separately C) It decreases the value of its parameter within a loop D) It calls itself
D
What are the three main devices used in algorithms?
Decisions: -if statements, allows different paths depending on the conditions Iterations: -(while, do-while and for, for each loops) Recursion: -(calls itself, with parameters reduced with each call) --Iterations/Recursion help fold the task into one or several mini-tasks that are repeated multiple times.
How are factorials defined and write an example of one:
Factorial numbers (i.e., n!) defined recursively: -factorial(0) = 1 -factorial(n+1) = factorial(n) * n+1 Examples: 0! = 1 1! = 1 * 1 = 1 2! = 2 * 1 * 1 = 2 3! = 3 * 2 * 1 * 1 = 6 4! = 4 * 3 * 2 * 1 * 1 = 24
What is the difference between using recursion vs. iteration?
Recursion calls the same method, iteration goes through a loop
What is the difference between a sequential search and a binary search? When would you use each of the searches?
Sequential goes in order and the list doesn't need to be in any particular order. Binary is used on a list that is in some order (numerical or alpha), it divides and conquers by finding the middle and eliminating portions of the list that do not satisfy the condition.
Given code: public void sort(int[] a) { for (int I = 1; i< a.length; i++) //Line 1 { int current = a[i]; //Line 2 int j = 0; //Line 3 while (a[j] < current) //Line 4 { j++ //Line 5 } for (int k = I; k> j; k--) //Line 6 { a[k] = a[k-1]; //Line 7 } a[j] = current; //Line 8 } } a) The sorting algorithm implemented in the sort method can be best described as : b) Given int[]a = {24,16,68,56,32}. What will be the results after the statement on Line 8 in sort completes for the second time?
a) Insertion sort. The while loop finds the right spot to insert current. The for loop shifts the elements in a to the right to make room. b) 16, 24, 32, 56, 68 a[1] and a[2] haven been inserted in the right places, so the first 3 elements are now in ascending order.
Quicksort questions: a) What comparisons does it take? b) What is the worst case? c) What is the best case? d) What is the algorithm?
a) Takes roughly n·log2 n comparisons. b) May get slow if pivot consistently fails to split the array into approximately equal halves. Its worst case run time behavior is O(n²). c) If the array is already sorted, and we always choose the first element (of the segment that is being sorted) as pivot, d) An O(n log n) algorithm.
Merge sort questions: a) What comparisons does it take? b) Is there a best or worst case? c) What is the algorithm?
a) Takes roughly n·log2 n comparisons. b) No c) An O(n log n) algorithm.
What is the pseudocode description of the execution of the selection sort algorithm?
for( each i from 0 to 4) { scan nums[i] through nums[5] for the smallest value swap nums[i] with the smallest element found in the scan } and/or for (each I from 0 to 4) { smallest = i for (each index between (I + 1 and 5) { if(nums[index] < nums{smallest]) { smallest = index } } swap nums[i] with nums[smallest] }
Pseudocode for merging the two sorted halves:
i1 = 0 //left index i2 = 0 //right index for (number of elements in entire array) { if (left value at i1 <= right value at i2) { include value from left array in new array i1++; } else { include value from right array in new array i2++ } }
public static int fact(int num) { int tmp = 1; for (int i = 1; i <= num; i++) { tmp *= i; } return tmp; }
iteration
What is an example of the code for insertion sort?
public class InsertionSorter { public static void sort(int[] a) { for (int i = 1; i < a.length; i++) { int next = a[i]; // Move all larger elements up int j = i; while (j > 0 && a[j - 1] > next) { a[j] = a[j - 1]; j--; } // Insert the element use next as place holder a[j] = next; } } }
Example of code for merge sort:
public static void merge(int[] result, int[] left, int[] right) { int i1 = 0; // index into left array int i2 = 0; //index into right array for (int i = 0; i < result.length; i++) { if (i2 >= right.length || (i1<left.length&&left[i1]<= right[i2])) { result[i] = left[i1]; // take from left i1++; } else { result[i] = right[i2]; // take from right i2++; } } }
What is an example of the code for selection sort?
public static void swap(int[] list, int i, int j) { int temp = list[i]; list[i] = list[j]; list[j] = temp; } and/or // places the elements of the given array into sorted order // using the selection sort algorithm // post: array is in sorted (nondecreasing) order public static void selectionSort(int[] a) { for (int i = 0; i < a.length - 1; i++) { // find index of smallest element int smallest = i; for (int j = i + 1; j < a.length; j++) { if (a[j] < a[smallest]) { smallest = j; } } swap(a, i, smallest); // swap smallest to front } }
public static int fact(int num) { if (num == 0) return 1; else return num * fact(num - 1); }
recursion