Cauvery Institute of Technology, Mandya: Divide and Conquer
Cauvery Institute of Technology, Mandya: Divide and Conquer
Technology, Mandya
Divide and Conquer
Minimum and Maximum Algorithm
Prof. Hemachander N,
Department of Computer Science &
Engineering,
CIT,Mandya
CIT,CSE
Recap
Boundary conditions of array
Binary search algorithm
Using divide and conquer [recursive approach]
Using Iterative procedure
Time Complexity- Best Case, Worst case and
average case
CIT,CSE
Finding the Maximum and Minimum
Problem Statement
CIT,CSE
Iterative Max_Min algorithm
Algorithm Straight_Max_Min(a[],n)
Purpose: Findig maximum and minimum element using Iterative procedure
Input: a- 1D array having n elements
n- size f the array a
Output: display max- maximum element, min- minimum element
Method:
max=min= a[0]
for i1 to n-1 do
if(a[i]>max) then
max=a[i]
end if
if(a[i]<min) then
min=a[i]
end if
end for
print max, min
END
CIT,CSE
Analyzing the Straight Forward Method
CIT,CSE
Max_Min algorithm using Recursion
Algorithm MaxMin(i, j, max, min)
Purpose: is to set max and min to the largest and smallest values in a[i:j].
Input: a[1:n] is a global array. Parameters i and j are integers, // 1≤i≤j≤n.
i= beginning index
J= ending index
Output: max- largest element in a
min- smallest element in a
Method:
if (i=j) then max min a[i]; //Small(P)
else if (i=j-1) then // Another case of Small(P)
{
if (a[i] < a[j]) then
max a[j]; min a[i];
else max a[i]; min a[j];
}
else
{
// if P is not small, divide P into sub-problems.
// Find where to split the set.
mid ( i + j )/2;
// Solve the sub-problems.
MaxMin( i, mid, max, min );
MaxMin( mid+1, j, max1, min1 );
// Combine the solutions.
if (max < max1) then max max1;
if (min > min1) then min min1;
}
END
CIT,CSE
Trace
Elements: [10,20,30,40,50,60,70,80,90,100]
max: 100
min: 10
CIT,CSE
Time Recurrence relation
• T(n) represents the time complexity of
Max_Min algorithm and it is represented as
follws:
CIT,CSE
Time Complexity using Masters
Theorem
• T(n)= 2 T(n/2) +2
• Here a=2, b=2, f(n)=2
• Find d? i.e., d=nd 2* n0, Hence d=0
• a>bd ,i.e., 2>20, 2>1
• Thus for e.g. a=2, b=2 & d=0; hence, since a>bd
• Master theorm states that,
• T(n)€ θ(nlogb a) = θ(nlog2 2) = θ(n)
CIT,CSE
Time Complexity
using
Substitution
Method
CIT,CSE
Next Video
• Merge Sort
CIT,CSE