Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Question 1 Divide-and-Conquer
Suppose you are given an array A with n entries, with each entry holding a distinct number. You are told that the sequence of values A[1], A[2], . . . , A[n] is unimodal: For some index p between 1 and n the values in the array entries increase up to position p in A and then decrease the remainder of the way until position n. (So if you were to draw a plot with the array position j on the x-axis and the value of the entry A[j ] on the y -axis tile plotted points would rise until x-value p, where theyd achieve their maximum and then fall from there on.) Youd like to nd the peak entry p without having to read the entire arrayin fact, by reading as few entries of A as possible Show how to nd the entry p by reading at most O(log n) entries of A. (Hint : Assume n = 2k and nd the recurrence of the running time) Solution: Look at the value A[n/2] and its adjacent values: 1. if A[n/2 1] < A[n/2] < A[n/2 + 1] then p > n/2, we call recursively on entries n/2 + 1 through n. 2. if A[n/2 1] > A[n/2] > A[n/2 + 1] then p < n/2, we call recursively on entries 1 through n/2 1. 3. if A[n/2] > A[n/2 1] and A[n/2] > A[n/2 + 1] then p = n/2.
FindPeakEntry(A,a,b) m
a+b 2
if A[m] > A[m 1] and A[m] < A[m + 1] then FindPeakEntry(A,m + 1,b) else if A[m] < A[m 1] and A[m] > A[m + 1] then FindPeakEntry(A,a, m 1) else return m
So we get the following recurrence: S [i, 0] = i and S [0, j ] = j , for any 0 i n, 0 j m. If i, j > 0 then: S [i 1, j ] + 1, S [i, j ] = min S [i, j 1] + 1, S [i 1, j 1] + 1, xi = yj