2 Divide and Conquer - Finding Min and Max
2 Divide and Conquer - Finding Min and Max
INTRODUCTION
DIVIDE AND
CONQUER
CONQUE OPTIONAL
DIVID R
E COMBIN
E
DIVIDE AND
CONQUER
Key Factors of Divide and Conquer Strategy:
1.Divide
If the problem is small, then solve it directly. Otherwise, divide the problem into smaller
subsets of the same problem.
2. Conquer
Conquer the smaller sub problems by solving(dividing) them recursively. If the sub-
problems are small enough, recursion is not needed it can be solved directly.
3. Combine
Take the solutions of the sub-problems and merge them into a solution to the original
problem.
DIVIDE AND
CONQUER
DIVIDE AND CONQUER
A[0….4]
12 0 -1 3 16
PROBLEM DEFINITION:
Consider P an arbitrary problem instance, represented as,
P=(n, a[i]…..a[j]), where
n-no of elements in the list a[i]…a[j].
Direct way
of finding
SMALL
VALUE solution?
ENOUGH
PROBLEM? OF n?
Small(P)???..
DIVIDE AND CONQUER -SOLUTION
LIST OF ELEMENTS
22,13-5,-8,15,60,17,31,47
N=9
EXAMPLE 1
60
D&C MAX
22,13 -5,-8,15,60,17,31,47 ALGORITHM -8
0 1 2 3 4 5 6 7 8 MIN
N=9
0,8,__,__
0,4,__,__ 5,8,__,__
0,1,__,__ 2,2,__,__
22,13 -5,-8,15,60,17,31,47
0 1 2 3 4 5 6 7 8
0,8,60,-8
0,4,22,-8 5,8,60,17
0,4,__,__ 5,8,__,__
SEARCHING:BINARY
SEARCH ALGORITHM
PROBLEM STATEMENT
PROBLEM DEFINITION:
Consider P an arbitrary problem instance, represented as,
P=(a, i,l,x), where
list a[i]…a[l] and x is the element to be searched.
Small(P)???
• Pick an index q (in the range [i,l])
• Compare x with a[q].
• There are 3 possibilities:
IF n=1,only one element in the list, (1) x = a[q]: problem P is immediately solved.
then compare x with a[i],if ‘x’ is equal (2) x < a[q]:x has to be searched for only in the
to a[i],then return 1 otherwise -1 sublist (a[i],a[i+1]…a[q-1]),hence P is
P(a,i,q-1,x)
(3) x >a[q]:x has to be searched for only in the
P has more than 1 element??? sublist (a[q+1],a[q+2]…a[l]),hence P is
DIVIDE AND CONQUER P(a,q+1,l,x)
BINARY SEARCH:EXAMPLE
-86 -37 -23 0 5 18 21 64 97
Compare 18 and
low middle element.
Searching for 18. middle
high
element found
18==18->equal
35
BINARY SEARCH:RECURSIVE ALGORITHM
BINARY SEARCH:ITERATIVE ALGORITHM
BINARY SEARCH:EXAMPLE
SEARCH 151
SEARCH-14
SEARCH 9
BINARY SEARCH:EXAMPLE
BINARY SEARCH-COMPLEXITY