The Lumenary · Grades 9–12
Algorithms, correctness and efficiency
Name: ______________________
Date: ______________________
You will learn to
- Implement linear search, binary search and insertion sort, and trace them on examples
- Prove an algorithm correct with a loop invariant and a decreasing measure, for binary search and for Euclid's algorithm
- Prove that binary search on items makes at most comparisons, and that insertion sort makes at most
- Prove that every comparison-based sorting method needs at least comparisons in the worst case, which grows like
- Compare growth rates such as , , , and , and explain why faster computers do not make efficiency irrelevant
- 1.
What is the largest number of comparisons binary search can make on a sorted list of entries?
- 2.
How many comparisons does insertion sort make, in the worst case, to sort a list of entries?
- 3.
This loop adds up a list of length :
s = 0 for i in range(n): # i = 0, 1, ..., n - 1 s = s + a[i]Which statement is a loop invariant that holds at the start of each pass (before is added) and proves that is the total at the end?
- A.
- B.
- C.
- D.
- 4.
A classmate's sorting function passed random tests on lists of up to numbers. Which statement is correct?
- A.This is evidence that the function works, but it does not prove it works on every list.
- B.It is now proved correct for all lists of length at most .
- C.It is proved correct, since is a large number of tests.
- D.The tests are useless; only proofs matter.
- 5.
An algorithm takes steps on inputs of size . A new computer is times faster. In the time the old computer needed for size , the new one can handle size . What is ?
- 6.
In the correctness proof of binary search, suppose . Why may we discard the indices ?
- A.The list is sorted, so for every : none of these entries equals .
- B.Because is the middle, so is equally likely to be in either half.
- C.Because we have already compared with all of .
- D.Because .
- 7.
Let
r := bsearch p lo hi. Which Lean proposition says thatris the first point where the testpgivestrue?- A.
p r = true ∧ ∀ k, k < r → p k = false - B.
p r = true - C.
∃ k, p k = true - D.
∀ k, k < r → p k = true
- A.
- 8.
Write
binary_search(a, t)for a sorted lista. Return a pair(index, probes): an indexiwitha[i] == t(or-1iftis absent), and the number of times you comparedtwith an entry of the list. The tests check correctness on many lists and thatprobesnever exceeds , which islen(a).bit_length()in Python.Computational — Practice
- 9.
Using the decision-tree argument (Theorem 6), what is the smallest number of comparisons that any comparison-based method could need, in the worst case, to sort different numbers?
- 10.
Run Euclid's algorithm on . How many divisions with remainder does it perform before reaching a pair whose second number is ? (Count every step .)