Divide and Conquer



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




 

divide&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])


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




Back to Top

III. Second Application: Quicksort

 

Partition (in/out A[p:q]): partitions the array A[p:q] and returns the position where the partition element A[p] ends up

function Partition(in/out A[p:q]) begin int i,j; real a=A[p]; i=p; j=q; while (i <= j) do while (A[i] <= a && i<=q) do i++; endwhile while (A[j] > a) do j--; endwhile if i < j then swap (A[i],A[j]); i++; j--; endif endwhile swap(A[p],A[j]); return(j); end