






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







CMPS 214 Problem Set 3
Style guide and expectations: Please see the Homework part of the syllabus for guidance on what we are looking for in homework solutions. We will grade according to these standards. You should cite all sources you used outside of the course material.
What we expect: Make sure to look at the We are expecting blocks below each problem to see what we will be grading for in each problem!
We suggest you do these on your own. As with any homework problem, though, you may ask the course sta for help.
[NOTE: These exercise questions will not be graded for this homework only, but we strongly recommend doing them as it will be good practice for the upcoming exam.]
[We are expecting: pseudocode, an english description of the main idea of the algo- rithm, as well as an informal explanation of correctness and runtime]
Solution: Given an array of length n, split the array into two halves of size n 2 each and recursively compute their respective majority elements. If both arrays have the same majority element, then it must be the majority element of the whole array, otherwise, one of the two majority elements found has to be the majority of the whole array, so we count the occurrences of each of the two majority elements in the array of length n and we are subsequently able to gure out the majority element of the array of length n.
As an exercise, try to prove the two claims in bold above, work on writing the al- gorithm in pseudocode, and then write its recurrence relation and prove its runtime.
If the arrays are unsorted, what should rst come to mind is copying both arrays into an array of length 2 n, sorting the resulting array in O(n log n), and then re- turning the middle element of the nal array. If we are looking to directly use the median-of-medians algorithm to get our median, the result may not be the exact median of the array, so we may not directly use the median-of-medians algorithm.
We can actually solve this problem in worst-case linear time even if the input arrays are unsorted. You can nd a sketch of the solution below: We rst start by concatenating the two input arrays. What we do next is we select a pivot using the median-of-medians algorithm and we partition based on the pivot. After partitioning, if the index of the pivot is the middle of the array, we are done as we have found our median. Otherwise, if the index of the pivot is bigger than the middle of the array, that means that the median is to the left of the pivot, so we discard everything that comes after it and we recurse on its left. Otherwise, we recurse on its right.
The details of the implementation, as well as a thorough proof of correctness and of the linear worst-case running time, can be found in Section 9.3 of CLRS. (b) If the arrays are sorted, can you do better? [We are expecting: A short English description, Pseudocode, runtime analysis.] Solution:
If the arrays are sorted, the naive solution would be to merge the two arrays, then return the middle element of the merged array. This can be done in O(n), but we can do better than that.
We can reduce the search space by half at every iteration (we remove half of each of the two arrays at every iteration), which would make the algorithm run in O(log n). Get the medians of the original two arrays: if the median of the rst array is bigger than the median of the second array, then discard the rst half of the second array and the second half of the rst array. Otherwise, discard the rst half of the rst array and the second half of the second array.
The implementation, the proof that the reduction is safe (i.e. that we never
Try the problems on your own before asking questions. Write up your answers yourself, in your own words. You should never share your typed- up solutions with your collaborators.
[NOTE: The following questions will be graded.]
Algorithm Monte Carlo or Las Vegas?
Expected running time
Worst-case running time
Probability of return- ing a majority element
Algorithm 1 Algorithm 2 Algorithm 3 [We are expecting: Your lled in-table, and a short justication for each entry of the table. You may use asymptotic notation for the running times; for the probability of returning a majority element, give the tightest bound that you can given the information provided. Fill in the table below, and justify your answers.]
The algorithms can be found in the PDF of this assignment's given
Solution:
Algorithm Monte Carlo or Las Vegas?
Expected running time
Worst-case running time
Probability of return- ing a majority element
Algorithm 1 Las Vegas O(n) undened 1 Algorithm 2 Monte Carlo O(n) O(n) 1 21011 Algorithm 3 Las Vegas O(n) O(n^2 ) 1
If an algorithm is a Las Vegas algorithm, it is always correct, which implies that the probability of returning a majority element is always 1. For Monte Carlo algorithms, we will need to do some calculations in order to gure out what the probability of returning the majority element is.
Explanation for Algorithm 1: Algorithm 1 keeps selecting a random element from the population and checking whether it is the majority element; if it is, the element is returned. Therefore, the algorithm never returns an element that is not the majority element, so it is always correct, and it is a Las Vegas algorithm.
Expected running time: The expected running time itself has a worst case. This worst case is achieved by minimizing the probability of picking a majority element, so we shall assume that the probability of picking a majority element is 12 (practically, this would require a population of innite size, but let us stick with it anyway).
Now, we would like to gure out the expected number of iterations, given that we know that the probability of picking a majority element is 12 and that we are sampling uniformly.
The probability of stopping at the kth^ iteration (getting k 1 non majority elements followed by a majority element) is given by (^21) k. The expected number of iterations is therefore: ∑ 1 i=1 i^ * P(i^ iterations) =^
i=
i 2 i^.
If you remember your calculus, it should be fairly easy to see that this series converges. We therefore know that the number of expected iterations is a constant, and since every iteration runs in O(n), the runtime of the entire algorithm is O(n) itself.
(Side note: the series evaluates to 2, and while knowing what the value of the constant is does not make any dierence in Big-Oh terms, it is still good to know that we are dealing with a "small" constant.)
Worst-case running time: In the worst case, the algorithm will keep selecting elements that are not the majority
Expected running time: Using an argument that is similar to the one we used for the rst algorithm, it is evident that the expected number of iterations is a constant, and since each iteration is O(n), it follows that the entire algorithm is expected to run in O(n).
Worst-case running time: In the worst case, the input will contain exactly n 2 + 1 majority elements, and after ran- domly reordering the elements, they will all be found at the end of the reordered array, so isMajority (which is an O(n) algorithm) will be called a total of n 2 times, therefore the worst-case running time of algorithm 3 is O(n^2 ).
Algorithm 1 getNumInversions(A) 1: numInv er sions 0 2: for i = 0 to A.size() - 1 do 3: for j = i + 1 to A.size() do 4: if A[i] > A[j] then 5: numInv er sions+ = 1 6: end if 7: end for 8: end for 9: return numInv er sions
The algorithm above checks every pair of indices (i; j) ( 0 i < j < n) and increments numInversions whenever a pair is found such that A[i] > A[j]. (b) Describe an O(n log n) algorithm to count the number of inversions in a given array. [Hint: Think about how you can modify MergeSort to solve this problem.] [We are expecting: Pseudocode, and a short English description explaining the main idea of the algorithm.We are also Expecting an informal justication of cor- rectness and of the running time.] Solution: As the hint suggests, the answer to this part is based o of MergeSort. Given an array of size n, an inversion (i; j) can either be entirely found in the left or right half of the array, or it can go across the middle of the array. Recursive calls take care of counting inversions contained entirely in either half of the array, while inversions across its middle have to be accounted for in the merge step. We still have to show how we can count the number of inversions, given two sorted arrays of size n 2 each, in f (n), such that T (n) in T (n) = 2T (n 2 ) + f (n) is O(n log n). I claim that I am able to count the number of inversions, given two sorted arrays of size n 2 each, in O(n). In fact, I am able to do that without modifying the merge function too much.
Each duck has a favorite activity: honking, eating, or simply doing nothing (idling). And since they are ducks, they do whatever they like to do all day long. You'd like to sort the ducks so that all the honking ducks are on the left, the eating ducks are on the right, and the idling ducks are in the middle.^1 You can only do two types of operations on the ducks: Operation Result ask(j) Ask the duck in position j about its favorite activity swap(i,j) Swap the duck in position j with the duck in position i You want to sort the ducks as soon as possible, but each of the above operations takes a constant time to execute. Also, you didn't bring a piece of paper or a pencil, so you can't write anything down and have to rely on your memory. Like many humans, you can remember up to seven integers^2 between 0 and n 1 at a time. (a) Design an algorithm to sort the ducks which takes O(n) seconds, and requires you to remember no more than seven integers^3 between 0 and n 1 at a time.
[We are expecting: Pseudocode AND a short English description of your algo- rithm.] Solution: What we want to do here is group the ducks based on their types, and using a constant amount of auxiliary storage. This should remind you of an algorithm that was covered in class, partition! With very small changes to partition, we should be able to sort the ducks in O(n) time using no more than seven integers. (^1) Having honking and eating ducks close would be disastrous. Don't ask why. (^2) see, e.g., https://en.wikipedia.org/wiki/The_Magical_Number_Seven,_Plus_or_Minus_Two (^3) You don't need to use all seven storage spots, but you can if you want to. Can you do it with only two?
Algorithm 4 duckPartition(A) 1: n length(A) 2: idlingStar t 0 3: eatingStar t 0 4: for i = 0 to n - 1 do 5: cur DuckT y pe A:ask(i) 6: if cur DuckT y pe == 1 then 7: A:sw ap(idlingStar t; i) 8: A:sw ap(eatingStar t; i) 9: idlingStar t + + 10: eatingStar t + + 11: else if cur DuckT y pe == 2 then 12: A:sw ap(eatingStar t; i) 13: eatingStar t + + 14: end if 15: end for
We need to keep track of the starting indices for the three duck types. Whenever a honking duck is found, the start indices of the other two types are shifted to the right (lines 8 and 9). Whenever an idle duck is found, the start index of the eating type is shifted to the right (line 14). The rest of the code is straightforward: whenever we encounter an eating duck, we do not change its spot as the third segment of the traversed subarray is dedicated for eating ducks. Whenever we encounter an idling duck, it is swapped with the rst eating duck in order to main- tain the invariant. Finally, whenever we encounter a honking duck, it is swapped with the rst idling duck: the honking duck is in the correct spot, but the idling duck it was swapped with is now misplaced, so we have to exchange the swapped idling duck with the rst eating duck, and then we are done! (b) Justify why your algorithm is correct, why it takes only O(n) seconds, and why it requires you to remember no more than seven integers at a time. [We are expecting: Informal justications of the correctness, runtime, and mem- ory usage of your algorithm that are both clear and convincing to the grader. If it's easier for you to be clear, you can give a formal proof of correctness, but you do not have to. It is okay to appeal to the correctness of an algorithm that we have seen in class, as long as you clearly explain the relationship between the two algorithms.] Solution: The algorithm keeps track of 5 variables: n which is the length of the array, the 2 start indices of the 2 rightmost duck types, the loop counter i, and the type of the duck we are currently pointing at (1 is honking, 2 is idling and 3 is eating).