Module2 ADA_4225_BCS401_12-03-2025
Module2 ADA_4225_BCS401_12-03-2025
Department of
ISE
Divide and conquer involves three steps, at each
level of recursion.
• Divide: Divide the problem into a number of sub
problems
• Conquer: Conquer the sub problems by solving them
recursively. If the sub – problem sizes are small enough,
then solve the sub- problem in a straight forward manner.
• Combine: combine the solutions to the sub- problems to
get the solution to the original problem.
Divide-and-Conquer Technique (cont.)
a problem of size n
(instance)
subproblem 1 subproblem 2
of size n/2 of size n/2
a solution to a solution to
subproblem 1 subproblem 2
Where,
T(n) is the time for divide and conquer method on any input of size n and
g(n) is the time to compute answer directly for small inputs.
The function f(n) is the time for dividing the problem ‘p’ and combining the
solutions to sub problems.
Recurrence equation for Divide and Conquer:
For divide and conquer based algorithms that produce sub problems of the
same type as the original problem, it is very natural to first describe them by
using recursion.
More generally, an instance of size n can be divided into b instances of size
n/b, with a of them needing to be solved. (Here, a and b are constants; a>=1
and b > 1.). Assuming that size n is a power of b(i.e. n=bk), to simplify our
analysis, we get the following recurrence for the running time T(n):
..... (1)
where f(n) is a function that accounts for the time spent on dividing the
problem into smaller ones and on combining their solutions.
The recurrence relation can theorem. be solved by i) substitution method or by
using ii) master theorem.
1. Substitution Method - This method repeatedly makes substitution for each
occurrence of the function T in the right-hand side until all disappear. such
occurrences
2. Master Theorem - The efficiency analysis of many divide-and-conquer
algorithms is greatly simplified by the master theorem. It states that, in
recurrence equation
T(n) = aT(n/b) + f (n), If f (n)∈ Θ (nd) where d ≥ 0 then
Department of
ISE
Binary Search (Iterative)
Algorithm Binary_Search( A[0…n-1], Key)
Input: Given an array of n elements in sorted order and key is an element to be searched.
Output: Returns the position of key element, if successful and returns -1 otherwise.
1. Set first = 0, last = n-1
2. While (first < = last)
mid = (first +last) / 2
if (key == A[mid])
return (mid+1); // successful
else if ( key < A[mid] )
last = mid – 1
else first = mid+1
end while
3. return -1 // unsuccessful Department of
ISE
Recursive binary search algorithm
Algorithm Binary_Search( A[0…n-1], Key)
Input: Given an array of n elements in sorted order and key is an element to be searched.
Output: Returns the position of key element, if successful and returns -1 otherwise.
1. Set first = 0, last = n-1
2. While (first < = last)
mid = (first +last) / 2
if (key == A[mid])
return (mid+1); // successful
else if ( key < A[mid] )
return Binary_Search( A{0, …., mid-1], key)
else Binary_Search( A{mid+1,……n-1], key)
end while
3. return -1 // unsuccessful Department of
ISE
Analysis
Best Case: Best case occurs, when we are searching the middle
element itself. In that case, total number of comparisons required is
1. there fore best case time complexity of binary search is Ω(1).
Worst Case: Let T(n) be the cost involved to search ‘n’ elements. Let
T(n/2) be the cost involved to search either left part or the right
part of an array.
Analysis
T(n) = a if n = 1
T(n/2) + b otherwise
Department of
ISE
Analysis
Average Case:
The average case occurs when an element is found some where
in the recursive calls, but not till the recursive call ends.
The average number of key comparisons made by binary search is only slightly
smaller than that in this worst case.
T(n) = log 2n
The average number of comparison in a successful search is
T(n) = log 2n – 1
The average number of comparison in a unsuccessful search is
T(n) = log 2n + 1
Department of
ISE
Merge Sort Algorithm
Mergesort(low, high)
//Given an array A of n elements. This algorithm sorts the elements in
//ascending order. The variables low and high are used to identify the
//positions of first and last element in each partition.
1. If (low< high)
2. mid = (low+high)/2;
3. Mergesort (low,mid);
4. Mergesort(mid+1,high);
5. Merge(low,mid,high);
6. End if
7. Exit
Merge Algorithm
Merge(low, mid, high)
// The variables low, mid, and high are used to identify the portions of elements in each
partition.
1. Initialize i=low, j= mid+1, h=low;
2. while ((h <= mid) && (j <= high))
3. if (a[h] < a[j])
b[i++] = a[h++];
else
b[i++] = a[j++];
4. if (h > mid)
for(k = j; k <= high; k++)
b[i++] = a[k];
else
for (k = h; k <= mid; k++)
b[i++] = a[k];
5. for (k = low; k <= high; k++)
a[k] = b[k];
Mergesort
• Split array A[0..n-1] into about equal halves and make copies of
each half in arrays B and C
• Sort arrays B and C recursively
• Merge sorted arrays B and C into array A as follows:
– Repeat the following until no elements remain in one of the
arrays:
• compare the first elements in the remaining unprocessed
portions of the arrays
• copy the smaller of the two into A, while incrementing the index
indicating the unprocessed portion of that array
– Once all elements in one of the arrays are processed, copy the
remaining unprocessed elements from the other array into A.
Analysis of Mergesort
The non-recursive
version of
Mergesort
starts from merging
single elements into
sorted pairs.
Quicksort
Quicksort is the other important sorting algorithm that is based on the divide-and-conquer
approach. Unlike mergesort, which divides its input elements according to their position in the
array, quicksort divides ( or partitions) them according to their value.
A partition is an arrangement of the array’s elements so that all the elements to the left of
some element A[s] are less than or equal to A[s], and all the elements to the right of A[s] are
greater than or equal to it:
Obviously, after a partition is achieved, A[s] will be in its final position in the sorted array, and
we can continue sorting the two subarrays to the left and to The right of A[s] independently
(e.g., by the same method).
In quick sort, the entire workhappens in the division stage, with no work required to combine
the solutions to the subproblems.
Quicksort Algorithm
Quick sort(low, high)
// A is an array of elements.
// The variables low and high are used to identify the positions of
first and
// last elements in each partition.
If(low< high) then
J= partition(low, high)
Quick sort( low, j-1)
Quick sort(j+1, high)
End if Exit
Partition(low, high)
Partition Algorithm
//This procedure partitions the element into two lists and places the pivot
//element into a appropriate place. Low = first element of the array, high =
//last element of the array, a[low] = pivot.
Step 1. Set pivot = a[low];
i = low +1;
j = high;
Step 2. Repeat step 3 while (a[i] < pivot && i < high)
Step 3. i++;
Step 4. Repeat step 5 while (a[j] > pivot)
Step 5. j--;
Step 6. If(i<j)
swap a[i] and a[j]
go to step 2
else
swap a[j] and pivot
Step 7. Return (j)
Analysis of Quicksort
• Best case: split in the middle — Θ(n log n)
• Worst case: sorted array! — Θ(n2)
• Average case: random arrays — Θ(n log n)
Multiplication of Large Integers
Consider the problem of multiplying two (large) n-digit integers
represented by arrays of their digits such as:
A = 12345678901357986429 B = 87654321284820912836
an b1 b2 …
bn
(d10) d11d12 … d1n
(d20) d21d22 … d2n
…………………
(dn0) dn1dn2 … dnn
First Divide-and-Conquer
Algorithm
A small example: A B where A = 2135 and B = 4014
A = (21·102 + 35), B = (40 ·102 + 14)
So, A B = (21 ·102 + 35) (40 ·102 + 14)
= 21 40 ·104 + (21 14 + 35 40) ·102 + 35 14
• Brute-force algorithm
A1 = 1, A2 =2, A3 = 3, A4 = 4
B1 = 1, B2 = 1, B3 = 2, B4 = 2
1. D = A1(B2 – B4) = 1(1 – 2) = -1
2. E = A4(B3-B1) = 4(2-1) = 4
3. F = (A3 + A4) B1 = (3+4)1 = 7
4. G = (A1 + A2)B4 = (1+2)2 = 6
5. H = (A3 – A1) (B1 + B2) = (3-1)(1+1) = 4
6. I = (A2 – A4)(B3+B4) = (2-4)(2+2) = -8
7. J = (A1+A4)(B1+B4) = (1+4)(1+2) = 15
M1 + M4 - M5 + M7 M3 + M5
=
M2 + M4 M1 + M3 - M2 + M6
Formulas for Strassen’s Algorithm
M1 = (A00 + A11) (B00 + B11)
A1 A2 B1 B2
10 21 01 01
41 10 21 04
01 30 20 11
50 21 13 50
A3 A4 B3 B4
1. D = A1 (B2 – B4)
01 11
10 -
* 04 50
41
10 -1 0
*
41 -5 4
-6 0
-9 4
2. E = A4 (B3 – B1)
Department
Department of of ISE
ISE
Analysis of Strassen’s Algorithm
If n is not a power of 2, matrices can be padded with zeros.
Number of multiplications:
M(n) = M(1) = 1
7M(n/2),
M(n) = 7M(2 k-1)
= 7[7M(2 k-2)] = 7 k M(2 k-k)] = 7 k (1)
= 7 2 M(2 k-2)]
Solution: M(n) = 7log 2 = n 2 ≈ n vs. n of brute-force
alg. n log 7 2.807 3
Advantages and Disadvantages
• Difficult problems is broken down into sub
problems and each sub problem is solved
independently.
• It gives efficient algorithms like quick sort,
merge sort, streassen’s matrix multiplication.
• Sub problems can be executed on parallel
processor.
Disadvantage
• It makes use of recursive methods and
the recursion is slow and complex.
Decrease-and-Conquer
The decrease and conquer technique is almost similar to the
divide and conquer technique, but instead of dividing the
problem into size n/2, it is decremented by a constant or
constant factor.
There are three variations of decrease and conquer
• Decrease by a constant
• Decrease by a constant factor
• Variable size decrease
The problems can be solved either top down (recursively)
or bottom up ( without recursion)
Decrease by a constant
• In this type of variation, the size of an instance
is reduced by the same constant ‘1’ on each
iteration. So, if a problem is of size ‘n’ , then a
sub problem of size ‘n-1’ is solved first but
before a sub sub problem of size ‘n-2’ is solved
and so on.
Decrease by a constant
Example: Consider a problem for computing a n
where n is a positive integer exponent
Let f(n) = a n
a n = a n-1 . a
= a n-2 . a . a F(n) = f(n-1 ) . a if n> 1
a if n
=a .a.a.a
n-3
=1
= a. a. a. a. . . n times
The above definition is a recursive definition i.e, a top down approach
Department of
ISE
Decrease by a constant factor
Example: Consider a problem for computing an
As the problem is to be halved each time (Since
the constant factor is 2, to solve a n, first solve
an/2
, but before solve an/4 and so on.
an
= (an/2 ) 2
if n is even and > 1
if n is odd and >
(a n-1/2 ) 2
a if1n = 1
Decrease by a constant factor
c d c d
b a c d
e f g h
2. Source Removal Algorithm
This is a direct implementation of Decrease and Conquer Method
Algorithm follow these steps
1. From a given graph find a vertex with no incoming edges.
Delete it along with all the edges outgoing from it.
2. Note the vertices that are deleted.
3. All these recorded vertices give Topologically sorted list.
Department of
ISE
Source Removal Algorithm
Repeatedly identify and remove a source (a vertex with no
incoming edges) and all the edges incident to it until either no
vertex is left or there is no source among the remaining
vertices (not a dag)
a b c d
Example: 1
e f g h
Efficiency: same as efficiency of the DFS-based algorithm, but how would you
identify a source? How do you remove a source from the dag?
a d
Example 2 c
b e
Department
Department of of ISE
ISE
Source Removal Algorithm
Topological Sort(G)
1. Find the indegree INDG(n) of each node n
of G.
2. Put in a queue Q all the nodes with zero
indegree.
3. Repeat step 4 and 5 until G becomes
empty.
4. Repeat the element n of the queue Q and
add it to T (Set Front = Front +1).
Source Removal Algorithm
5.Repeat the following for each neighbour, m of
the node n
a) Set INDEG(m) = INDG(m)-1
b) If INDEG(m) = 0 then add m to the rear
end of the Q.
6. Exit.
Department
Department of of ISE
ISE
Questions???
1. Explain the divide and conquer technique.
2. Write an algorithm for merge sort and quick sort.
3. Apply merge sort algorithm to sort the elements 8,3, 2, 9, 7, 1, 5, 4.
4. Explain Decrease and conquer. Or What are the three major variations of decrease and
conquer technique?
5. Design an insertion sort algorithm and obtain its time complexity. Apply insertion sort
on these elements. 25,75,40,10,20,
6. Explain Strassen’s matrix multiplication and derive its time complexity
7. Explain topological sorting with example.
8. Apply source removal method to obtain topological sort for the given graph.