# Use the partition procedure from mergesort to reorder the array so that the numbers less than n/2 are in the first half of the array, while the other numbers are in the second half of the array. |
# Use the partition procedure from quicksort to reorder the array so that the numbers less than n/2 are in the first half of the array, while the other numbers are in the second half of the array. |
|
2.
1 Hour | 2 Hours | |
log n | 236*108 | 272*108 |
sqrt(n) | 1296*1019 | 5184*1019 |
n | 36*108 | 72*108 |
n log n | 1.33*108 | 2.58*108 |
n2 | 60000 | 8.49*104 |
n3 | 1532.62 | 1930.98 |
2n | 31 | 32 |
n! | 12 | 13 |
3.
We want the following inequality to hold for a constant c when n ≥ n0:
4.
Algorithm (Input: X = (a1, a2, a3,.. an), Output: A = (A1, A2, ..., An)
1. A[1] = X[1]
2. print A[1]
3. for i=2 to n
4. ___ A[i] = A[i-1] + X[i]
5. ___ print A[i]
6. end for
Complexity: The algorithm clearly runs in O(n) time.
Correctness: Clearly, A[i] = a[1] + a[2] + ... + a[i]. (prove by induction on i if you want to be formal).
5.
(tasters) Let n be the number of bottles. Let k = ⌈ log2 n ⌉ and choose k testers, call them 1,2,..,k. There are 2k ≥ n subsets of {1,2,...,k}. For i = 1,2,...,n, pair the i'th bottle with the i'th subset Si of {1,2,...,k}, and have the tasters in that subset taste the i'th bottle.
If the i'th bottle is poisoned, then at the end of the month, exactly those tasters in the set Si will die. This will identify which bottle is poisoned.
(missing number) Here are two algorithms. Let the array be A[1..n-1].
Algorithm 1:
Algorithm 2:
Total time: n + n/2 + n/4 + n/8 + ... = O(n)