CS2223
HW#6

Due: Monday , December 8

1. (6 points) Suppose that given an integer constant n and an array declared int T[n], you know that T is partially sorted  in the sense that there exists an integer m , 0≤m≤n-1, such thatT[0]≤T[1]≤...≤T[m] and T[m+1]≤T[m+2]≤...≤T[n-1].  However, you do not know the value of m.  Show that T can be sorted in worst-case time O(n).  A precise pseudo-code description of your algorithm is acceptable.

2. (5 points) A hidden memory consumption of QuickSort is the system stack. That is, each nontrivial invocation (invocation for a list of length at least two) of quicksort causes two new invocations. While the first of these new invocations is being processed, the a set of parameters are placed in the system stack.
	(a) How large can the ststem stack get?
	 (b) Describe a modification of quicksort which would limit the worst-case size
	      of the system stack to O(lgn), where n is the number of elements in the list
	      to be quicksorted.

3. (6 points) A typical dynamic programming algorithm provides the cost of a solution or establishes the existence of a solution without actually constructing the solution.  To see how to construct a solution by using an efficient mechanism which tests for the existence of a solution, solve the following:
  You are given a boolean function BlackBox  of two inputs:
   -a list of integers x1,x2,...,xn,
   -an integer q,
and you are told that, in time O(1), BlackBox will return "true" if there is some subset of x1,x2,...,xn  whose sum is q and false otherwise.  Design an algorithm (a program is not needed) with the same input which will return an actual subset of x1,x2,...,xn whose sum is q, if such a subset exists, or it should return "failure".
  For example, BlackBox( (23,27,41,72,-4,6), 29) would return "true", but your algorithm with the same input would return (27,-4,6).  Your algorithm may call BlackBox as often as it wishes and it should work in time O(n).

CS2223
HW#6 Solutions

1. m :=0;
      do m++; while ((T[m]<=T[m+1]) && (m<n-1));   /* Find m */
     if m <n -1 
          MERGE(T[0..m],T[m+1..n-1 ],T[1..n-1])

2. (a) The stack can contain n-1 elements, where n is the number of elements to be quicksorted.
(b) Always process (quicksort) the shorter list while pushing the longer list onto the stack. 

3. S  := (x1,x2,...,xn)
     if !BlackBox (S, q) return ("failure")         	O(1)
     for (i = 1; i<= n; i++)	n  times
        S  = S  - xi 
           if !BlackBox (S, q)                     /*we really need xi ; put it back */
                                                    S  = S  + xi;
      return S ;	  O (1)

Since the body of the loop is executed in O(1) time, the time to execute the loop (and the program) is O(n).