Divide and Conquer
Divide and Conquer
CONQUER
selinao@uonbi.ac.ke
Divide-and-Conquer
• Maintainance:
Analyzing divide and conquer
algorithms
• When an algorithm contains a recursive call its running time is
described by a recurrence.
• A recurrence: is an equation that describes the overall running
time on a problem of size n in terms of the running time on
smaller inputs
• Let T(n) be the running time on a problem of size n
• If the problem size is small enough the straightward solution
takes constant time which we write as O(1)
• Suppose that the subdivision of the problem yields a sub
problem each of which is 1/b the size of the original problem.
• It takes time T(n/b) to solve one sub problem of size n/b and
so it takes time aT(n/b) to solve a sub problems
Analyzing divide and conquer
algorithms
• If we take D(n) time to divide the problem into sub problems
and c(n) time to combine the solution to the original problem
we get the recurrence
• When the lists A and B are sorted and known to be in disjoint ordered
ranges
• all of elements of A are smaller than all those of B
• If A and B are stored as consecutive sub-arrays, then merge actually needs
no work at all:
• Just “forget the boundary”
Description of quicksort
• Quicksort, like merge sort, applies the divide-and-conquer
paradigm introduced. Here is the three-step divide-and-
conquer process for sorting a typical array (A,p- r).
• Divide: Choose a pivot q and Partiton or rearrange the array
into two sub arrays A[p—q-1] and A[q+1—r] such that the sub
array A[p—q-1] contains elements less than q and the sub
array A[q+1—r] contains elements greater than q.
• Conquer: sort the two sub arrays A[p—q-1] and A[q+1—r by
making recursive calls to quicksort
• Combine: Because the subarrays are already sorted, no work
is needed to combine them: the entire array A[p– r] is now
sorted
Pseudo code for quicksort
quicksort(A,p,r)
if p<r
q=partition(A,p,r)
Quicksort(A, p,q-1)
Quicksort(A,q+1,r)
Partition(A,p,r)
x=A[r]
i=p-1
for(j=p to r-1)
if A[j]≤x
i=i+1
exchange A[i] with A[j]
exchange A[i+1] with A[r]
return(i+1)
Worst case running time of
quicksort
• The worst case for quick-sort occurs when the pivot is the
unique minimum or maximum element
• The best case for quick-sort occurs when the pivot is the
median element
• The Land R parts are equal –the sequence is split in halves, like
in merge sort
• Thus, the best-case running time of quick-sort is O(n log n)