Divide and Conquer

# Divide and Conquer - Divide and Conquer...

This preview shows pages 1–4. Sign up to view the full content.

I. Template for Divide and Conquer II. First Application: Mergesort III. Second Application: Quicksort IV. First Application: Order Statistics I. Template for Divide and Conquer input I) begin if (size of input is small enough) then solve directly; return ; endif divide I into two or more parts I1, I2,. ..; call divide&conquer(I1) to get a subsolution S1; call divide&conquer(I2) to get a subsolution S2; ... Merge the subsolutions S1, S2,. ..into a global solution S; end Back to Top II. First Application: Mergesort Procedure Mergesort(input A[1:n], i,j; output B[1:n]) sorts A[i:j] and puts the result in B[i:j]) Divide and Conquer http://www.seas.gwu.edu/~ayoussef/cs212/divide-and-conquer.html 1 of 8 9/3/2010 4:51 AM

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Procedure Mergesort ( input A[1:n], i,j; output B[1:n]) begin Datatype C[1:n]; If i=j then B[i] = A[i]; Return; endif Mergesort (A,i,(i+j)/2;C); /* sorts the first half*/ Mergesort(A,(i+j)/2 +1,j;C); /* sorts the second half*/ Merge(C,i,j;B); /* merges the two sorted halves * * into a single sorted list */ end Procedure Merge( input : C i,j; output : B) begin int k=(i+j)/2; int u,v,w; /* u will scan C[i:k], v will scan C[k+1:j], and w will index the out B*/ u=i; v=k+1; w=u; while (u <= k and v <= j) do if C[u] <= C[v] then B[w]=C[u]; u++;w++; else B[w]=C[v]; v++;w++; endif endwhile If u > k then Put C[v:j] in B[w:j]; Elseif v>j Put C[u:k] in B[w:j]; endif end Time Complexity of Merge (for i=1, j=n): O(n) = cn, for some constant c; Time complexity of Mergesort T(n): T(n) = 2T(n/2) + cn T(n) =2T(n/2)+cn T(n) = 2T(n/2) + cn T(n/2)=2T(n/4)+cn/2 2T(n/2) = 4T(n/4) + 2cn/2 T(n/4)=2T(n/4)+cn/4 4T(n/4) = 8T(n/4) + 4cn/4 . . . . . . T(2) =2T(1)+c*2 (n/2)T(2) = nT(1) + (n/2)c*2 Divide and Conquer http://www.seas.gwu.edu/~ayoussef/cs212/divide-and-conquer.html 2 of 8 9/3/2010 4:51 AM
------------------- -------------------------------- add and cancel: T(n) = nT(1) +cn+cn+. ..+cn = nT(1)+cnlog n = O(nlog n) Back to Top III. Second Application: Quicksort take any arbitrary element of the input array A[1:n]. Assume we take the leftmost element, A[1]; partition A[1:n] around A[1] into two parts: the left part consisting of elements <= A[1], and the right part consisting of elements \> A[1]

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 8

Divide and Conquer - Divide and Conquer...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online