Data Str & Algorithm HW Solutions 59

Data Str & Algorithm HW Solutions 59 - 9.6 Count H...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
59 } 9.3 At each step, the exponent, call it x , is cut in half. This can only happen log x times. Of course, x = log n . Thus, the total cost is O (loglog n ) . 9.4 The partition and f ndpivot functions remain the same. template <class Elem, class Comp> int findK(Elem A[], int i, int j, Elem K) { if (j <= i) return i; // Don’t sort 0 or 1 Elem int pivotindex = findpivot(A, i, j); swap(A, pivotindex, j); // Put pivot at end // k will be the first position in the right subarray int k = partition<Elem,Comp>(A, i-1, j, A[j]); swap(A, k, j); // Put pivot in place if (Comp.eq(A[k], K)) return k; if ([k], K)) return findK<Elem,Comp>(A, i, k-1, K); else return findK<Elem,Comp>(A, k+1, j, K); } 9.5 Binary search is faster since the self-organizing search cost grows faster. Note, however, that self-organizing search may be faster when the time to sort prior to binary search is an important factor.
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 9.6 Count: H G E D C A B F; the number of searches is 53. Move-to-front: G H E C D A B F; the number of searches is 59. Transpose: A B D E H G C F; the number of searches is 95. 9.7 For count, visit each record in turn in the order that will visit the last element each time. For example, if for the values 0 to 7 stored in ascending order initially, visit them in reverse order (from 7 down to 0). For Move-to-Front, again visit in reverse order. For Transpose, alternately visit the last two elements, as described in the book. 9.8 template <class Elem> void FreqCount(Elem A, int count) { // Assume that array is empty to begin with int n = 0; while ((int val = GETNEXT()) != DONE) { for (i=0; i<n; i++) if (A[i] == val) break; if (i == n) { A[n] = val; count[n++] = 1; }...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online