SlideShare a Scribd company logo
Unit II
BRUTE FORCE AND DIVIDE-AND-
CONQUER
PART 1
Dr.S.Gunasundari
Associate Professor
CSE Dept
Syllabus
Brute Force
 Computing an
 String matching
 Closest-Pair
 Convex Hull Problems
 Exhaustive Search
Traveling Salesman Problem
 Knapsack Problem
Assignment problem.
Divide and conquer
• Merge sort
• Quick sort
• Binary search-
• Closest Pair
• Multiplication of Large Integers
09-03-2022
Brute Force
A straightforward approach, usually based directly on the problem’s statement and definitions
of the concepts involved
Examples:
1. Computing an (a > 0, n a nonnegative integer)
2. Computing n!
3. Multiplying two matrices
4. Searching for a key of a given value in a list
09-03-2022
Brute-Force Sorting Algorithm
Selection Sort
Scan the array to find its smallest element and swap it with the first element.
Then, starting with the second element, scan the elements to the right of it
to find the smallest among them and swap it with the second element.
Generally, on pass i (0  i  n-2), find the smallest element in A[i..n-1] and
swap it with A[i]:
09-03-2022
Example
09-03-2022
Analysis of Selection Sort
09-03-2022
09-03-2022
Time Efficiency
09-03-2022
Bubble sort
Consecutive adjacent pairs of elements in the array
are compared with each other.
If the element at the lower index is greater than the
element at the higher index
the two elements are interchanged so that the
element is placed before the bigger one.
This process will continue till the list of unsorted
elements exhausts
09-03-2022
Example
09-03-2022
Code and Example
09-03-2022
Example
09-03-2022
Time Efficiency
09-03-2022
Computing an
 an = a * a * a …..(n times)
 a – non-zero number
 n- non negative integer
 Compute an by multiplying a by n times
09-03-2022
Brute-Force String Matching
 pattern: a string of m characters to search for
 text: a (longer) string of n characters to search in
 problem: find a substring in the text that matches the pattern
Brute-force algorithm
Step 1 Align pattern at beginning of text
Step 2 Moving from left to right, compare each character of pattern to the corresponding
character in text until
 all characters are found to match (successful search); or
 a mismatch is detected
Step 3 While pattern is not found and the text is not yet exhausted, realign pattern one
position to the right and repeat Step 2
09-03-2022
Examples of Brute-Force String Matching
1. Pattern: 001011
Text: 10010101101001100101111010
1. Pattern: happy
Text: It is never too late to have a happy childhood.
09-03-2022
Example
09-03-2022
Pseudocode and Efficiency Efficiency:
09-03-2022
Closest-Pair Problem
Find the two closest points in a set of n points (in the two-dimensional Cartesian plane).
Brute-force algorithm
Compute the distance between every pair of distinct points n(n-1)/2 pairs and return the
indexes of the points for which the distance is the smallest.
09-03-2022
Closest-Pair Brute-Force Algorithm (cont.)
09-03-2022
Analysis
 Basic Operation: Computing Euclidean distance
 Avoid finding square roots
 Now basic operation is squaring the number
09-03-2022
Convex Hull
 The convex hull problem is the problem of
constructing the convex hull for a given set S
of n points
 Definition A set of points (finite or infinite) in
the plane is called convex if for any two points
P and Q in the set, the entire line segment with
the endpoints at P and Q belongs to the set
09-03-2022
09-03-2022
Convex Hull Brute Force Algorithm
 A line segment connecting two points Pi and Pj of a set of n points is a part of its
convex hull’s boundary
 if and only if all the other points of the set lie on the same side of the straight line through
these two points
 Repeating this test for every pair of points yields a list of line segments that make up
the convex hull’s boundary
09-03-2022
09-03-2022
Analysis of Convex Hull Brute Force Algorithm
 The time efficiency of this algorithm is in O(n3)
 for each of n(n-1)/ 2 pairs of distinct points, we may need to find the sign of ax +
by - c for each of the other n - 2 points
09-03-2022
Brute-Force Strength and Weakness
 Strengths
 wide applicability
 simplicity
 yields reasonable algorithms for some important problems
(e.g., matrix multiplication, sorting, searching, string matching)
 Weaknesses
 rarely yields efficient algorithms
 some brute-force algorithms are unacceptably slow
 not as constructive as some other design techniques
09-03-2022
Exhaustive Search
A brute force solution to a problem involving search for an element with a special
property, usually among combinatorial objects such as permutations, combinations,
or subsets of a set.
Method:
 generate a list of all potential solutions to the problem in a systematic manner
 evaluate potential solutions one by one, disqualifying infeasible ones and, for an
optimization problem, keeping track of the best one found so far
 when search ends, announce the solution(s) found
09-03-2022
Example 1: Traveling Salesman Problem
 Given n cities with known distances between each pair, find the shortest tour that passes
through all the cities exactly once before returning to the starting city
 Alternatively: Find shortest Hamiltonian circuit in a weighted connected graph
 Hamiltonian circuit is defined as a cycle that passes through all the vertices of the graph exactly once.
 Graph Vertices represent cities
 Edge weight represent distance
 Example:
a b
c d
8
2
7
5 3
4
09-03-2022
TSP by Exhaustive Search
Tour Cost
a→b→c→d→a 2+3+7+5 = 17
a→b→d→c→a 2+4+7+8 = 21
a→c→b→d→a 8+3+4+5 = 20
a→c→d→b→a 8+7+4+2 = 21
a→d→b→c→a 5+4+3+8 = 20
a→d→c→b→a 5+7+3+2 = 17
a b
c d
8
2
7
5 3
4
09-03-2022
we can get all the tours by generating all the permutations of n − 1 intermediate
cities, compute the tour lengths, and find the shortest among them
Efficiency: (n-1)!
• Some pair of tours differ by direction
• a→b→c→d→a AND a→d→c→b→a
• we could cut the number of vertex permutations by half ((n-1)!)/2
Example
09-03-2022
Example 2: Knapsack Problem
Given n items:
 weights: w1 w2 … wn
 values: v1 v2 … vn
 a knapsack of capacity W
Find most valuable subset of the items that fit into the knapsack
Example: Knapsack capacity W=16
item weight value
1 2 $20
2 5 $30
3 10 $50
4 5 $10
09-03-2022
Knapsack Problem by Exhaustive Search
Subset Total weight Total value
{1} 2 $20
{2} 5 $30
{3} 10 $50
{4} 5 $10
{1,2} 7 $50
{1,3} 12 $70
{1,4} 7 $30
{2,3} 15 $80
{2,4} 10 $40
{3,4} 15 $60
{1,2,3} 17 not feasible
{1,2,4} 12 $60
{1,3,4} 17 not feasible
{2,3,4} 20 not feasible
{1,2,3,4} 22 not feasible
Efficiency:
09-03-2022
Since
the number of subsets of an n-element set is 2n, the
exhaustive search leads to a (2n) algorithm, no
matter how efficiently individual subsets are
generated.
Example
09-03-2022
Example 3: The Assignment Problem
There are n people who need to be assigned to n jobs, one person per job. The
cost of assigning person i to job j is C[i,j]. Find an assignment that minimizes the
total cost.
Job 0 Job 1 Job 2 Job 3
Person 0 9 2 7 8
Person 1 6 4 3 7
Person 2 5 8 1 8
Person 3 7 6 9 4
Algorithmic Plan: Generate all legitimate assignments, compute
their costs, and select the cheapest one.
How many assignments are there?
09-03-2022
Assignment Problem by Exhaustive Search
9 2 7 8
6 4 3 7
5 8 1 8
7 6 9 4
Assignment (col.#s) Total Cost
1, 2, 3, 4 9+4+1+4=18
1, 2, 4, 3 9+4+8+9=30
1, 3, 2, 4 9+3+8+4=24
1, 3, 4, 2 9+3+8+6=26
1, 4, 2, 3 9+7+8+9=33
1, 4, 3, 2 9+7+1+6=23
etc.
C =
09-03-2022
Since the number of permutations to be
considered for the general case of the
assignment problem is n!,
Assignment Total Cost
2,1,3,4 2+6+1+4=13
2,1,4,3 2+6+8+9=25
2,3,1,4 2+3+5+4=14
2,3,4,1 2+3+8+7=20
2,4,1,3 2+7+5+9=23
2,4,3,1 2+7+1+7=17
09-03-2022
AssignmentTotal Cost
3,1,2,4 7+6+8+4=25
3,1,4,2 7+6+8+6=27
3,2,1,4 7+4+5+4=20
3,2,4,1 7+4+8+7=26
3,4,1,2 7+7+5+6=25
3,4,2,1 7+7+8+7=29
09-03-2022
AssignmentTotal Cost
4,1,2,3 8+6+8+9=31
4,1,3,2 8+6+1+6=21
4,2,1,3 8+4+5+9=26
4,2,3,1 8+4+1+7=20
4,3,1,2 8+3+5+6=22
4,3,2,1 8+3+8+7=26
09-03-2022
Solution
09-03-2022
Final Comments on Exhaustive Search
 Exhaustive-search algorithms run in a realistic amount of time only on very small
instances
 In some cases, there are much better alternatives!
 Euler circuits
 shortest paths
 minimum spanning tree
 assignment problem
 In many cases, exhaustive search or its variation is the only known way to get
exact solution
09-03-2022
Divide-and-Conquer
The most-well known algorithm design strategy:
1. Divide instance of problem into two or more smaller instances
2. Solve smaller instances recursively
3. Obtain solution to original (larger) instance by combining these solutions
09-03-2022
Divide-and-Conquer Technique (cont.)
subproblem 2
of size n/2
subproblem 1
of size n/2
a solution to
subproblem 1
a solution to
the original problem
a solution to
subproblem 2
a problem of size n
09-03-2022
Divide-and-Conquer Examples
 Sorting: mergesort and quicksort
 Binary tree traversals
 Binary search (?)
 Multiplication of large integers
 Matrix multiplication: Strassen’s algorithm
 Closest-pair and convex-hull algorithms
09-03-2022
General Divide-and-Conquer Recurrence
T(n) = aT(n/b) + f (n) where f(n)  (nd), d  0
Master Theorem: If a < bd, T(n)  (nd)
If a = bd, T(n)  (nd log n)
If a > bd, T(n)  (nlog b a )
Note: The same results hold with O instead of .
Examples: T(n) = 4T(n/2) + n  T(n)  ?
T(n) = 4T(n/2) + n2  T(n)  ?
T(n) = 4T(n/2) + n3  T(n)  ?
09-03-2022
Mergesort
 Split array A[0..n-1] in two 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.
09-03-2022
Pseudocode of Mergesort
09-03-2022
Pseudocode of Merge
09-03-2022
Mergesort Example
8 3 2 9 7 1 5 4
8 3 2 9 7 1 5 4
8 3 2 9 7 1 5 4
8 3 2 9 7 1 5 4
3 8 2 9 1 7 4 5
2 3 8 9 1 4 5 7
1 2 3 4 5 7 8 9
09-03-2022
Analysis of Mergesort
 All cases have same efficiency: Θ(n log n)
 Number of comparisons in the worst case is close to theoretical minimum for
comparison-based sorting:
log2 n! ≈ n log2 n - 1.44n
 Space requirement: Θ(n) (not in-place)
 Can be implemented without recursion (bottom-up)
09-03-2022
Quicksort
 Select a pivot (partitioning element) – here, the first element
 Rearrange the list so that all the elements in the first s positions are smaller than or equal to the pivot
and all the elements in the remaining n-s positions are larger than or equal to the pivot (see next slide
for an algorithm)
 Exchange the pivot with the last element in the first (i.e., ) subarray — the pivot is now in its final
position
 Sort the two subarrays recursively
p
A[i]p A[i]p
09-03-2022
Partitioning Algorithm
09-03-2022
Quicksort Example
5 3 1 9 8 2 4 7
09-03-2022
Analysis of Quicksort
 Best case: split in the middle — Θ(n log n)
 Worst case: sorted array! — Θ(n2)
 Average case: random arrays — Θ(n log n)
 Improvements:
better pivot selection: median of three partitioning
switch to insertion sort on small subfiles
elimination of recursion
These combine to 20-25% improvement
 Considered the method of choice for internal sorting of large files (n ≥ 10000)
09-03-2022
Binary Search
Very efficient algorithm for searching in sorted array:
K
vs
A[0] . . . A[m] . . . A[n-1]
If K = A[m], stop (successful search); otherwise, continue
searching by the same method in A[0..m-1] if K < A[m]
and in A[m+1..n-1] if K > A[m]
l  0; r  n-1
while l  r do
m  (l+r)/2
if K = A[m] return m
else if K < A[m] r  m-1
else l  m+1
return -1
09-03-2022
Analysis of Binary Search
 Time efficiency
worst-case recurrence: Cw (n) = 1 + Cw( n/2 ), Cw (1) = 1
solution: Cw(n) = log2(n+1)
This is VERY fast: e.g., Cw(106) = 20
 Optimal for searching a sorted array
 Limitations: must be a sorted array (not linked list)
 Bad (degenerate) example of divide-and-conquer
 Has a continuous counterpart called bisection method for solving equations in one unknown f(x) = 0 (see
Sec. 12.4)
09-03-2022
Binary Tree Algorithms
Binary tree is a divide-and-conquer ready structure!
Ex. 1: Classic traversals (preorder, inorder, postorder)
Algorithm Inorder(T)
if T   a a
Inorder(Tleft) b c b c
print(root of T) d e d e
Inorder(Tright)
Efficiency: Θ(n)
09-03-2022
Binary Tree Algorithms (cont.)
Ex. 2: Computing the height of a binary tree
T T
L R
h(T) = max{h(TL), h(TR)} + 1 if T   and h() = -1
Efficiency: Θ(n)
09-03-2022
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
The grade-school algorithm:
a1 a2 … an
b1 b2 … bn
(d10) d11d12 … d1n
(d20) d21d22 … d2n
… … … … … … …
(dn0) dn1dn2 … dnn
Efficiency: n2 one-digit multiplications
09-03-2022
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
In general, if A = A1A2 and B = B1B2 (where A and B are n-digit,
A1, A2, B1, B2 are n/2-digit numbers),
A  B = A1  B1·10n + (A1  B2 + A2  B1) ·10n/2 + A2  B2
Recurrence for the number of one-digit multiplications M(n):
M(n) = 4M(n/2), M(1) = 1
Solution: M(n) = n2
09-03-2022
Second Divide-and-Conquer Algorithm
A  B = A1  B1·10n + (A1  B2 + A2  B1) ·10n/2 + A2  B2
The idea is to decrease the number of multiplications from 4 to 3:
(A1 + A2 )  (B1 + B2 ) = A1  B1 + (A1  B2 + A2  B1) + A2  B2,
I.e., (A1  B2 + A2  B1) = (A1 + A2 )  (B1 + B2 ) - A1  B1 - A2  B2,
which requires only 3 multiplications at the expense of (4-1) extra add/sub.
Recurrence for the number of multiplications M(n):
M(n) = 3M(n/2), M(1) = 1
Solution: M(n) = 3log 2n = nlog 23 ≈ n1.585
09-03-2022
Example of Large-Integer Multiplication
2135  4014
09-03-2022
Strassen’s Matrix Multiplication
Strassen observed [1969] that the product of two matrices can be computed as follows:
C00 C01 A00 A01 B00 B01
= *
C10 C11 A10 A11 B10 B11
M1 + M4 - M5 + M7 M3 + M5
=
M2 + M4 M1 + M3 - M2 + M6
09-03-2022
Formulas for Strassen’s Algorithm
M1 = (A00 + A11)  (B00 + B11)
M2 = (A10 + A11)  B00
M3 = A00  (B01 - B11)
M4 = A11  (B10 - B00)
M5 = (A00 + A01)  B11
M6 = (A10 - A00)  (B00 + B01)
M7 = (A01 - A11)  (B10 + B11)
09-03-2022
Analysis of Strassen’s Algorithm
If n is not a power of 2, matrices can be padded with zeros.
Number of multiplications:
M(n) = 7M(n/2), M(1) = 1
Solution: M(n) = 7log 2n = nlog 27 ≈ n2.807 vs. n3 of brute-force alg.
Algorithms with better asymptotic efficiency are known but they
are even more complex.
09-03-2022
Closest-Pair Problem by Divide-and-Conquer
Step 1 Divide the points given into two subsets S1 and S2 by a vertical line x = c so that half the points lie to
the left or on the line and half the points lie to the right or on the line.
09-03-2022
Closest Pair by Divide-and-Conquer (cont.)
Step 2 Find recursively the closest pairs for the left and right
subsets.
Step 3 Set d = min{d1, d2}
We can limit our attention to the points in the symmetric
vertical strip of width 2d as possible closest pair. Let C1
and C2 be the subsets of points in the left subset S1 and of
the right subset S2, respectively, that lie in this vertical
strip. The points in C1 and C2 are stored in increasing
order of their y coordinates, which is maintained by
merging during the execution of the next step.
Step 4 For every point P(x,y) in C1, we inspect points in
C2 that may be closer to P than d. There can be no more
than 6 such points (because d ≤ d2)!
09-03-2022
Closest Pair by Divide-and-Conquer: Worst Case
The worst case scenario is depicted below:
09-03-2022
Efficiency of the Closest-Pair Algorithm
Running time of the algorithm is described by
T(n) = 2T(n/2) + M(n), where M(n)  O(n)
By the Master Theorem (with a = 2, b = 2, d = 1)
T(n)  O(n log n)
09-03-2022
Quickhull Algorithm
Convex hull: smallest convex set that includes given points
 Assume points are sorted by x-coordinate values
 Identify extreme points P1 and P2 (leftmost and rightmost)
 Compute upper hull recursively:
 find point Pmax that is farthest away from line P1P2
 compute the upper hull of the points to the left of line P1Pmax
 compute the upper hull of the points to the left of line PmaxP2
 Compute lower hull in a similar manner
P1
P2
Pmax
09-03-2022
Efficiency of Quickhull Algorithm
 Finding point farthest away from line P1P2 can be done in linear time
 Time efficiency:
worst case: Θ(n2) (as quicksort)
average case: Θ(n) (under reasonable assumptions about
distribution of points given)
 If points are not initially sorted by x-coordinate value, this can be accomplished in O(n log n) time
 Several O(n log n) algorithms for convex hull are known
09-03-2022

More Related Content

What's hot

design and analysis of algorithm
design and analysis of algorithmdesign and analysis of algorithm
design and analysis of algorithm
Muhammad Arish
 
Unit 5
Unit 5Unit 5
Unit 5
guna287176
 
Branch and bound technique
Branch and bound techniqueBranch and bound technique
Branch and bound technique
ishmecse13
 
Branch and bound
Branch and boundBranch and bound
Branch and bound
Dr Shashikant Athawale
 
Greedy Algorithms
Greedy AlgorithmsGreedy Algorithms
Greedy Algorithms
Amrinder Arora
 
DS ppt
DS pptDS ppt
Slide1
Slide1Slide1
Dynamic Programming - Part II
Dynamic Programming - Part IIDynamic Programming - Part II
Dynamic Programming - Part II
Amrinder Arora
 
Backtracking & branch and bound
Backtracking & branch and boundBacktracking & branch and bound
Backtracking & branch and bound
Vipul Chauhan
 
CS 6402 – DESIGN AND ANALYSIS OF ALGORITHMS questio
CS 6402 – DESIGN AND ANALYSIS OF ALGORITHMS questioCS 6402 – DESIGN AND ANALYSIS OF ALGORITHMS questio
CS 6402 – DESIGN AND ANALYSIS OF ALGORITHMS questio
Karthik Venkatachalam
 
algorithm Unit 3
algorithm Unit 3algorithm Unit 3
algorithm Unit 3
Monika Choudhery
 
01. design & analysis of agorithm intro & complexity analysis
01. design & analysis of agorithm intro & complexity analysis01. design & analysis of agorithm intro & complexity analysis
01. design & analysis of agorithm intro & complexity analysis
Onkar Nath Sharma
 
Analysis of Algorithm
Analysis of AlgorithmAnalysis of Algorithm
Analysis of Algorithm
أحلام انصارى
 
5.1 greedy 03
5.1 greedy 035.1 greedy 03
5.1 greedy 03
Krish_ver2
 
Unit 3 daa
Unit 3 daaUnit 3 daa
Unit 3 daa
Nv Thejaswini
 
Branch and bound technique
Branch and bound techniqueBranch and bound technique
Branch and bound technique
ishmecse13
 
Divide and Conquer - Part 1
Divide and Conquer - Part 1Divide and Conquer - Part 1
Divide and Conquer - Part 1
Amrinder Arora
 
Unit 4
Unit 4Unit 4
Unit 4
guna287176
 
Graph Traversal Algorithms - Breadth First Search
Graph Traversal Algorithms - Breadth First SearchGraph Traversal Algorithms - Breadth First Search
Graph Traversal Algorithms - Breadth First Search
Amrinder Arora
 

What's hot (19)

design and analysis of algorithm
design and analysis of algorithmdesign and analysis of algorithm
design and analysis of algorithm
 
Unit 5
Unit 5Unit 5
Unit 5
 
Branch and bound technique
Branch and bound techniqueBranch and bound technique
Branch and bound technique
 
Branch and bound
Branch and boundBranch and bound
Branch and bound
 
Greedy Algorithms
Greedy AlgorithmsGreedy Algorithms
Greedy Algorithms
 
DS ppt
DS pptDS ppt
DS ppt
 
Slide1
Slide1Slide1
Slide1
 
Dynamic Programming - Part II
Dynamic Programming - Part IIDynamic Programming - Part II
Dynamic Programming - Part II
 
Backtracking & branch and bound
Backtracking & branch and boundBacktracking & branch and bound
Backtracking & branch and bound
 
CS 6402 – DESIGN AND ANALYSIS OF ALGORITHMS questio
CS 6402 – DESIGN AND ANALYSIS OF ALGORITHMS questioCS 6402 – DESIGN AND ANALYSIS OF ALGORITHMS questio
CS 6402 – DESIGN AND ANALYSIS OF ALGORITHMS questio
 
algorithm Unit 3
algorithm Unit 3algorithm Unit 3
algorithm Unit 3
 
01. design & analysis of agorithm intro & complexity analysis
01. design & analysis of agorithm intro & complexity analysis01. design & analysis of agorithm intro & complexity analysis
01. design & analysis of agorithm intro & complexity analysis
 
Analysis of Algorithm
Analysis of AlgorithmAnalysis of Algorithm
Analysis of Algorithm
 
5.1 greedy 03
5.1 greedy 035.1 greedy 03
5.1 greedy 03
 
Unit 3 daa
Unit 3 daaUnit 3 daa
Unit 3 daa
 
Branch and bound technique
Branch and bound techniqueBranch and bound technique
Branch and bound technique
 
Divide and Conquer - Part 1
Divide and Conquer - Part 1Divide and Conquer - Part 1
Divide and Conquer - Part 1
 
Unit 4
Unit 4Unit 4
Unit 4
 
Graph Traversal Algorithms - Breadth First Search
Graph Traversal Algorithms - Breadth First SearchGraph Traversal Algorithms - Breadth First Search
Graph Traversal Algorithms - Breadth First Search
 

Similar to Unit 2

Unit 2
Unit 2Unit 2
Unit 2
guna287176
 
Perform brute force
Perform brute forcePerform brute force
Perform brute force
SHC
 
A Comparative Analysis Of Assignment Problem
A Comparative Analysis Of Assignment ProblemA Comparative Analysis Of Assignment Problem
A Comparative Analysis Of Assignment Problem
Jim Webb
 
A0280115(1)
A0280115(1)A0280115(1)
A0280115(1)
prabhat k prasad
 
Matrix Multiplication(An example of concurrent programming)
Matrix Multiplication(An example of concurrent programming)Matrix Multiplication(An example of concurrent programming)
Matrix Multiplication(An example of concurrent programming)
Pramit Kumar
 
2.03.Asymptotic_analysis.pptx
2.03.Asymptotic_analysis.pptx2.03.Asymptotic_analysis.pptx
2.03.Asymptotic_analysis.pptx
ssuser1fb3df
 
APLICACIONES DE LA DERIVADA EN LA CARRERA DE (Mecánica, Electrónica, Telecomu...
APLICACIONES DE LA DERIVADA EN LA CARRERA DE (Mecánica, Electrónica, Telecomu...APLICACIONES DE LA DERIVADA EN LA CARRERA DE (Mecánica, Electrónica, Telecomu...
APLICACIONES DE LA DERIVADA EN LA CARRERA DE (Mecánica, Electrónica, Telecomu...
WILIAMMAURICIOCAHUAT1
 
Recursive algorithms
Recursive algorithmsRecursive algorithms
Recursive algorithms
subhashchandra197
 
Daa chapter 3
Daa chapter 3Daa chapter 3
Daa chapter 3
B.Kirron Reddi
 
Asssignment problem
Asssignment problemAsssignment problem
Asssignment problem
Mamatha Upadhya
 
Daa chapter 2
Daa chapter 2Daa chapter 2
Daa chapter 2
B.Kirron Reddi
 
Basic MATLAB-Presentation.pptx
Basic MATLAB-Presentation.pptxBasic MATLAB-Presentation.pptx
Basic MATLAB-Presentation.pptx
PremanandS3
 
Module 2 Design Analysis and Algorithms
Module 2 Design Analysis and AlgorithmsModule 2 Design Analysis and Algorithms
Module 2 Design Analysis and Algorithms
Cool Guy
 
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdfUnit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
yashodamb
 
dynamic programming complete by Mumtaz Ali (03154103173)
dynamic programming complete by Mumtaz Ali (03154103173)dynamic programming complete by Mumtaz Ali (03154103173)
dynamic programming complete by Mumtaz Ali (03154103173)
Mumtaz Ali
 
Sienna 4 divideandconquer
Sienna 4 divideandconquerSienna 4 divideandconquer
Sienna 4 divideandconquer
chidabdu
 
Seminar Report (Final)
Seminar Report (Final)Seminar Report (Final)
Seminar Report (Final)
Aruneel Das
 
Lecture 8 dynamic programming
Lecture 8 dynamic programmingLecture 8 dynamic programming
Lecture 8 dynamic programming
Oye Tu
 
Unit 2 in daa
Unit 2 in daaUnit 2 in daa
Unit 2 in daa
Nv Thejaswini
 
algorithm Unit 2
algorithm Unit 2 algorithm Unit 2
algorithm Unit 2
Monika Choudhery
 

Similar to Unit 2 (20)

Unit 2
Unit 2Unit 2
Unit 2
 
Perform brute force
Perform brute forcePerform brute force
Perform brute force
 
A Comparative Analysis Of Assignment Problem
A Comparative Analysis Of Assignment ProblemA Comparative Analysis Of Assignment Problem
A Comparative Analysis Of Assignment Problem
 
A0280115(1)
A0280115(1)A0280115(1)
A0280115(1)
 
Matrix Multiplication(An example of concurrent programming)
Matrix Multiplication(An example of concurrent programming)Matrix Multiplication(An example of concurrent programming)
Matrix Multiplication(An example of concurrent programming)
 
2.03.Asymptotic_analysis.pptx
2.03.Asymptotic_analysis.pptx2.03.Asymptotic_analysis.pptx
2.03.Asymptotic_analysis.pptx
 
APLICACIONES DE LA DERIVADA EN LA CARRERA DE (Mecánica, Electrónica, Telecomu...
APLICACIONES DE LA DERIVADA EN LA CARRERA DE (Mecánica, Electrónica, Telecomu...APLICACIONES DE LA DERIVADA EN LA CARRERA DE (Mecánica, Electrónica, Telecomu...
APLICACIONES DE LA DERIVADA EN LA CARRERA DE (Mecánica, Electrónica, Telecomu...
 
Recursive algorithms
Recursive algorithmsRecursive algorithms
Recursive algorithms
 
Daa chapter 3
Daa chapter 3Daa chapter 3
Daa chapter 3
 
Asssignment problem
Asssignment problemAsssignment problem
Asssignment problem
 
Daa chapter 2
Daa chapter 2Daa chapter 2
Daa chapter 2
 
Basic MATLAB-Presentation.pptx
Basic MATLAB-Presentation.pptxBasic MATLAB-Presentation.pptx
Basic MATLAB-Presentation.pptx
 
Module 2 Design Analysis and Algorithms
Module 2 Design Analysis and AlgorithmsModule 2 Design Analysis and Algorithms
Module 2 Design Analysis and Algorithms
 
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdfUnit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
 
dynamic programming complete by Mumtaz Ali (03154103173)
dynamic programming complete by Mumtaz Ali (03154103173)dynamic programming complete by Mumtaz Ali (03154103173)
dynamic programming complete by Mumtaz Ali (03154103173)
 
Sienna 4 divideandconquer
Sienna 4 divideandconquerSienna 4 divideandconquer
Sienna 4 divideandconquer
 
Seminar Report (Final)
Seminar Report (Final)Seminar Report (Final)
Seminar Report (Final)
 
Lecture 8 dynamic programming
Lecture 8 dynamic programmingLecture 8 dynamic programming
Lecture 8 dynamic programming
 
Unit 2 in daa
Unit 2 in daaUnit 2 in daa
Unit 2 in daa
 
algorithm Unit 2
algorithm Unit 2 algorithm Unit 2
algorithm Unit 2
 

More from GunasundariSelvaraj

Unit 5
Unit 5Unit 5
Unit 4
Unit 4Unit 4
Unit 3
Unit 3Unit 3
Unit 2
Unit 2Unit 2
Unit 1
Unit 1Unit 1
Unit i
Unit iUnit i
Unit 5
Unit 5Unit 5
Unit 4
Unit 4Unit 4
Unit 3
Unit 3Unit 3

More from GunasundariSelvaraj (9)

Unit 5
Unit 5Unit 5
Unit 5
 
Unit 4
Unit 4Unit 4
Unit 4
 
Unit 3
Unit 3Unit 3
Unit 3
 
Unit 2
Unit 2Unit 2
Unit 2
 
Unit 1
Unit 1Unit 1
Unit 1
 
Unit i
Unit iUnit i
Unit i
 
Unit 5
Unit 5Unit 5
Unit 5
 
Unit 4
Unit 4Unit 4
Unit 4
 
Unit 3
Unit 3Unit 3
Unit 3
 

Recently uploaded

CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
RamonNovais6
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
co23btech11018
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
21UME003TUSHARDEB
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
IJECEIAES
 
artificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptxartificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptx
GauravCar
 
cnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classicationcnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classication
SakkaravarthiShanmug
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
Divyanshu
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
Gino153088
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
shadow0702a
 
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have oneISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
Las Vegas Warehouse
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
Nada Hikmah
 
CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1
PKavitha10
 
Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
Mahmoud Morsy
 
john krisinger-the science and history of the alcoholic beverage.pptx
john krisinger-the science and history of the alcoholic beverage.pptxjohn krisinger-the science and history of the alcoholic beverage.pptx
john krisinger-the science and history of the alcoholic beverage.pptx
Madan Karki
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
ecqow
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
IJECEIAES
 

Recently uploaded (20)

CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
 
artificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptxartificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptx
 
cnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classicationcnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classication
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
 
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have oneISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
 
CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1
 
Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
 
john krisinger-the science and history of the alcoholic beverage.pptx
john krisinger-the science and history of the alcoholic beverage.pptxjohn krisinger-the science and history of the alcoholic beverage.pptx
john krisinger-the science and history of the alcoholic beverage.pptx
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
 

Unit 2

  • 1. Unit II BRUTE FORCE AND DIVIDE-AND- CONQUER PART 1 Dr.S.Gunasundari Associate Professor CSE Dept
  • 2. Syllabus Brute Force  Computing an  String matching  Closest-Pair  Convex Hull Problems  Exhaustive Search Traveling Salesman Problem  Knapsack Problem Assignment problem. Divide and conquer • Merge sort • Quick sort • Binary search- • Closest Pair • Multiplication of Large Integers 09-03-2022
  • 3. Brute Force A straightforward approach, usually based directly on the problem’s statement and definitions of the concepts involved Examples: 1. Computing an (a > 0, n a nonnegative integer) 2. Computing n! 3. Multiplying two matrices 4. Searching for a key of a given value in a list 09-03-2022
  • 4. Brute-Force Sorting Algorithm Selection Sort Scan the array to find its smallest element and swap it with the first element. Then, starting with the second element, scan the elements to the right of it to find the smallest among them and swap it with the second element. Generally, on pass i (0  i  n-2), find the smallest element in A[i..n-1] and swap it with A[i]: 09-03-2022
  • 6. Analysis of Selection Sort 09-03-2022
  • 9. Bubble sort Consecutive adjacent pairs of elements in the array are compared with each other. If the element at the lower index is greater than the element at the higher index the two elements are interchanged so that the element is placed before the bigger one. This process will continue till the list of unsorted elements exhausts 09-03-2022
  • 14. Computing an  an = a * a * a …..(n times)  a – non-zero number  n- non negative integer  Compute an by multiplying a by n times 09-03-2022
  • 15. Brute-Force String Matching  pattern: a string of m characters to search for  text: a (longer) string of n characters to search in  problem: find a substring in the text that matches the pattern Brute-force algorithm Step 1 Align pattern at beginning of text Step 2 Moving from left to right, compare each character of pattern to the corresponding character in text until  all characters are found to match (successful search); or  a mismatch is detected Step 3 While pattern is not found and the text is not yet exhausted, realign pattern one position to the right and repeat Step 2 09-03-2022
  • 16. Examples of Brute-Force String Matching 1. Pattern: 001011 Text: 10010101101001100101111010 1. Pattern: happy Text: It is never too late to have a happy childhood. 09-03-2022
  • 18. Pseudocode and Efficiency Efficiency: 09-03-2022
  • 19. Closest-Pair Problem Find the two closest points in a set of n points (in the two-dimensional Cartesian plane). Brute-force algorithm Compute the distance between every pair of distinct points n(n-1)/2 pairs and return the indexes of the points for which the distance is the smallest. 09-03-2022
  • 21. Analysis  Basic Operation: Computing Euclidean distance  Avoid finding square roots  Now basic operation is squaring the number 09-03-2022
  • 22. Convex Hull  The convex hull problem is the problem of constructing the convex hull for a given set S of n points  Definition A set of points (finite or infinite) in the plane is called convex if for any two points P and Q in the set, the entire line segment with the endpoints at P and Q belongs to the set 09-03-2022
  • 24. Convex Hull Brute Force Algorithm  A line segment connecting two points Pi and Pj of a set of n points is a part of its convex hull’s boundary  if and only if all the other points of the set lie on the same side of the straight line through these two points  Repeating this test for every pair of points yields a list of line segments that make up the convex hull’s boundary 09-03-2022
  • 26. Analysis of Convex Hull Brute Force Algorithm  The time efficiency of this algorithm is in O(n3)  for each of n(n-1)/ 2 pairs of distinct points, we may need to find the sign of ax + by - c for each of the other n - 2 points 09-03-2022
  • 27. Brute-Force Strength and Weakness  Strengths  wide applicability  simplicity  yields reasonable algorithms for some important problems (e.g., matrix multiplication, sorting, searching, string matching)  Weaknesses  rarely yields efficient algorithms  some brute-force algorithms are unacceptably slow  not as constructive as some other design techniques 09-03-2022
  • 28. Exhaustive Search A brute force solution to a problem involving search for an element with a special property, usually among combinatorial objects such as permutations, combinations, or subsets of a set. Method:  generate a list of all potential solutions to the problem in a systematic manner  evaluate potential solutions one by one, disqualifying infeasible ones and, for an optimization problem, keeping track of the best one found so far  when search ends, announce the solution(s) found 09-03-2022
  • 29. Example 1: Traveling Salesman Problem  Given n cities with known distances between each pair, find the shortest tour that passes through all the cities exactly once before returning to the starting city  Alternatively: Find shortest Hamiltonian circuit in a weighted connected graph  Hamiltonian circuit is defined as a cycle that passes through all the vertices of the graph exactly once.  Graph Vertices represent cities  Edge weight represent distance  Example: a b c d 8 2 7 5 3 4 09-03-2022
  • 30. TSP by Exhaustive Search Tour Cost a→b→c→d→a 2+3+7+5 = 17 a→b→d→c→a 2+4+7+8 = 21 a→c→b→d→a 8+3+4+5 = 20 a→c→d→b→a 8+7+4+2 = 21 a→d→b→c→a 5+4+3+8 = 20 a→d→c→b→a 5+7+3+2 = 17 a b c d 8 2 7 5 3 4 09-03-2022 we can get all the tours by generating all the permutations of n − 1 intermediate cities, compute the tour lengths, and find the shortest among them Efficiency: (n-1)! • Some pair of tours differ by direction • a→b→c→d→a AND a→d→c→b→a • we could cut the number of vertex permutations by half ((n-1)!)/2
  • 32. Example 2: Knapsack Problem Given n items:  weights: w1 w2 … wn  values: v1 v2 … vn  a knapsack of capacity W Find most valuable subset of the items that fit into the knapsack Example: Knapsack capacity W=16 item weight value 1 2 $20 2 5 $30 3 10 $50 4 5 $10 09-03-2022
  • 33. Knapsack Problem by Exhaustive Search Subset Total weight Total value {1} 2 $20 {2} 5 $30 {3} 10 $50 {4} 5 $10 {1,2} 7 $50 {1,3} 12 $70 {1,4} 7 $30 {2,3} 15 $80 {2,4} 10 $40 {3,4} 15 $60 {1,2,3} 17 not feasible {1,2,4} 12 $60 {1,3,4} 17 not feasible {2,3,4} 20 not feasible {1,2,3,4} 22 not feasible Efficiency: 09-03-2022 Since the number of subsets of an n-element set is 2n, the exhaustive search leads to a (2n) algorithm, no matter how efficiently individual subsets are generated.
  • 35. Example 3: The Assignment Problem There are n people who need to be assigned to n jobs, one person per job. The cost of assigning person i to job j is C[i,j]. Find an assignment that minimizes the total cost. Job 0 Job 1 Job 2 Job 3 Person 0 9 2 7 8 Person 1 6 4 3 7 Person 2 5 8 1 8 Person 3 7 6 9 4 Algorithmic Plan: Generate all legitimate assignments, compute their costs, and select the cheapest one. How many assignments are there? 09-03-2022
  • 36. Assignment Problem by Exhaustive Search 9 2 7 8 6 4 3 7 5 8 1 8 7 6 9 4 Assignment (col.#s) Total Cost 1, 2, 3, 4 9+4+1+4=18 1, 2, 4, 3 9+4+8+9=30 1, 3, 2, 4 9+3+8+4=24 1, 3, 4, 2 9+3+8+6=26 1, 4, 2, 3 9+7+8+9=33 1, 4, 3, 2 9+7+1+6=23 etc. C = 09-03-2022 Since the number of permutations to be considered for the general case of the assignment problem is n!,
  • 37. Assignment Total Cost 2,1,3,4 2+6+1+4=13 2,1,4,3 2+6+8+9=25 2,3,1,4 2+3+5+4=14 2,3,4,1 2+3+8+7=20 2,4,1,3 2+7+5+9=23 2,4,3,1 2+7+1+7=17 09-03-2022
  • 38. AssignmentTotal Cost 3,1,2,4 7+6+8+4=25 3,1,4,2 7+6+8+6=27 3,2,1,4 7+4+5+4=20 3,2,4,1 7+4+8+7=26 3,4,1,2 7+7+5+6=25 3,4,2,1 7+7+8+7=29 09-03-2022
  • 39. AssignmentTotal Cost 4,1,2,3 8+6+8+9=31 4,1,3,2 8+6+1+6=21 4,2,1,3 8+4+5+9=26 4,2,3,1 8+4+1+7=20 4,3,1,2 8+3+5+6=22 4,3,2,1 8+3+8+7=26 09-03-2022
  • 41. Final Comments on Exhaustive Search  Exhaustive-search algorithms run in a realistic amount of time only on very small instances  In some cases, there are much better alternatives!  Euler circuits  shortest paths  minimum spanning tree  assignment problem  In many cases, exhaustive search or its variation is the only known way to get exact solution 09-03-2022
  • 42. Divide-and-Conquer The most-well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances 2. Solve smaller instances recursively 3. Obtain solution to original (larger) instance by combining these solutions 09-03-2022
  • 43. Divide-and-Conquer Technique (cont.) subproblem 2 of size n/2 subproblem 1 of size n/2 a solution to subproblem 1 a solution to the original problem a solution to subproblem 2 a problem of size n 09-03-2022
  • 44. Divide-and-Conquer Examples  Sorting: mergesort and quicksort  Binary tree traversals  Binary search (?)  Multiplication of large integers  Matrix multiplication: Strassen’s algorithm  Closest-pair and convex-hull algorithms 09-03-2022
  • 45. General Divide-and-Conquer Recurrence T(n) = aT(n/b) + f (n) where f(n)  (nd), d  0 Master Theorem: If a < bd, T(n)  (nd) If a = bd, T(n)  (nd log n) If a > bd, T(n)  (nlog b a ) Note: The same results hold with O instead of . Examples: T(n) = 4T(n/2) + n  T(n)  ? T(n) = 4T(n/2) + n2  T(n)  ? T(n) = 4T(n/2) + n3  T(n)  ? 09-03-2022
  • 46. Mergesort  Split array A[0..n-1] in two 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. 09-03-2022
  • 49. Mergesort Example 8 3 2 9 7 1 5 4 8 3 2 9 7 1 5 4 8 3 2 9 7 1 5 4 8 3 2 9 7 1 5 4 3 8 2 9 1 7 4 5 2 3 8 9 1 4 5 7 1 2 3 4 5 7 8 9 09-03-2022
  • 50. Analysis of Mergesort  All cases have same efficiency: Θ(n log n)  Number of comparisons in the worst case is close to theoretical minimum for comparison-based sorting: log2 n! ≈ n log2 n - 1.44n  Space requirement: Θ(n) (not in-place)  Can be implemented without recursion (bottom-up) 09-03-2022
  • 51. Quicksort  Select a pivot (partitioning element) – here, the first element  Rearrange the list so that all the elements in the first s positions are smaller than or equal to the pivot and all the elements in the remaining n-s positions are larger than or equal to the pivot (see next slide for an algorithm)  Exchange the pivot with the last element in the first (i.e., ) subarray — the pivot is now in its final position  Sort the two subarrays recursively p A[i]p A[i]p 09-03-2022
  • 53. Quicksort Example 5 3 1 9 8 2 4 7 09-03-2022
  • 54. Analysis of Quicksort  Best case: split in the middle — Θ(n log n)  Worst case: sorted array! — Θ(n2)  Average case: random arrays — Θ(n log n)  Improvements: better pivot selection: median of three partitioning switch to insertion sort on small subfiles elimination of recursion These combine to 20-25% improvement  Considered the method of choice for internal sorting of large files (n ≥ 10000) 09-03-2022
  • 55. Binary Search Very efficient algorithm for searching in sorted array: K vs A[0] . . . A[m] . . . A[n-1] If K = A[m], stop (successful search); otherwise, continue searching by the same method in A[0..m-1] if K < A[m] and in A[m+1..n-1] if K > A[m] l  0; r  n-1 while l  r do m  (l+r)/2 if K = A[m] return m else if K < A[m] r  m-1 else l  m+1 return -1 09-03-2022
  • 56. Analysis of Binary Search  Time efficiency worst-case recurrence: Cw (n) = 1 + Cw( n/2 ), Cw (1) = 1 solution: Cw(n) = log2(n+1) This is VERY fast: e.g., Cw(106) = 20  Optimal for searching a sorted array  Limitations: must be a sorted array (not linked list)  Bad (degenerate) example of divide-and-conquer  Has a continuous counterpart called bisection method for solving equations in one unknown f(x) = 0 (see Sec. 12.4) 09-03-2022
  • 57. Binary Tree Algorithms Binary tree is a divide-and-conquer ready structure! Ex. 1: Classic traversals (preorder, inorder, postorder) Algorithm Inorder(T) if T   a a Inorder(Tleft) b c b c print(root of T) d e d e Inorder(Tright) Efficiency: Θ(n) 09-03-2022
  • 58. Binary Tree Algorithms (cont.) Ex. 2: Computing the height of a binary tree T T L R h(T) = max{h(TL), h(TR)} + 1 if T   and h() = -1 Efficiency: Θ(n) 09-03-2022
  • 59. 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 The grade-school algorithm: a1 a2 … an b1 b2 … bn (d10) d11d12 … d1n (d20) d21d22 … d2n … … … … … … … (dn0) dn1dn2 … dnn Efficiency: n2 one-digit multiplications 09-03-2022
  • 60. 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 In general, if A = A1A2 and B = B1B2 (where A and B are n-digit, A1, A2, B1, B2 are n/2-digit numbers), A  B = A1  B1·10n + (A1  B2 + A2  B1) ·10n/2 + A2  B2 Recurrence for the number of one-digit multiplications M(n): M(n) = 4M(n/2), M(1) = 1 Solution: M(n) = n2 09-03-2022
  • 61. Second Divide-and-Conquer Algorithm A  B = A1  B1·10n + (A1  B2 + A2  B1) ·10n/2 + A2  B2 The idea is to decrease the number of multiplications from 4 to 3: (A1 + A2 )  (B1 + B2 ) = A1  B1 + (A1  B2 + A2  B1) + A2  B2, I.e., (A1  B2 + A2  B1) = (A1 + A2 )  (B1 + B2 ) - A1  B1 - A2  B2, which requires only 3 multiplications at the expense of (4-1) extra add/sub. Recurrence for the number of multiplications M(n): M(n) = 3M(n/2), M(1) = 1 Solution: M(n) = 3log 2n = nlog 23 ≈ n1.585 09-03-2022
  • 62. Example of Large-Integer Multiplication 2135  4014 09-03-2022
  • 63. Strassen’s Matrix Multiplication Strassen observed [1969] that the product of two matrices can be computed as follows: C00 C01 A00 A01 B00 B01 = * C10 C11 A10 A11 B10 B11 M1 + M4 - M5 + M7 M3 + M5 = M2 + M4 M1 + M3 - M2 + M6 09-03-2022
  • 64. Formulas for Strassen’s Algorithm M1 = (A00 + A11)  (B00 + B11) M2 = (A10 + A11)  B00 M3 = A00  (B01 - B11) M4 = A11  (B10 - B00) M5 = (A00 + A01)  B11 M6 = (A10 - A00)  (B00 + B01) M7 = (A01 - A11)  (B10 + B11) 09-03-2022
  • 65. Analysis of Strassen’s Algorithm If n is not a power of 2, matrices can be padded with zeros. Number of multiplications: M(n) = 7M(n/2), M(1) = 1 Solution: M(n) = 7log 2n = nlog 27 ≈ n2.807 vs. n3 of brute-force alg. Algorithms with better asymptotic efficiency are known but they are even more complex. 09-03-2022
  • 66. Closest-Pair Problem by Divide-and-Conquer Step 1 Divide the points given into two subsets S1 and S2 by a vertical line x = c so that half the points lie to the left or on the line and half the points lie to the right or on the line. 09-03-2022
  • 67. Closest Pair by Divide-and-Conquer (cont.) Step 2 Find recursively the closest pairs for the left and right subsets. Step 3 Set d = min{d1, d2} We can limit our attention to the points in the symmetric vertical strip of width 2d as possible closest pair. Let C1 and C2 be the subsets of points in the left subset S1 and of the right subset S2, respectively, that lie in this vertical strip. The points in C1 and C2 are stored in increasing order of their y coordinates, which is maintained by merging during the execution of the next step. Step 4 For every point P(x,y) in C1, we inspect points in C2 that may be closer to P than d. There can be no more than 6 such points (because d ≤ d2)! 09-03-2022
  • 68. Closest Pair by Divide-and-Conquer: Worst Case The worst case scenario is depicted below: 09-03-2022
  • 69. Efficiency of the Closest-Pair Algorithm Running time of the algorithm is described by T(n) = 2T(n/2) + M(n), where M(n)  O(n) By the Master Theorem (with a = 2, b = 2, d = 1) T(n)  O(n log n) 09-03-2022
  • 70. Quickhull Algorithm Convex hull: smallest convex set that includes given points  Assume points are sorted by x-coordinate values  Identify extreme points P1 and P2 (leftmost and rightmost)  Compute upper hull recursively:  find point Pmax that is farthest away from line P1P2  compute the upper hull of the points to the left of line P1Pmax  compute the upper hull of the points to the left of line PmaxP2  Compute lower hull in a similar manner P1 P2 Pmax 09-03-2022
  • 71. Efficiency of Quickhull Algorithm  Finding point farthest away from line P1P2 can be done in linear time  Time efficiency: worst case: Θ(n2) (as quicksort) average case: Θ(n) (under reasonable assumptions about distribution of points given)  If points are not initially sorted by x-coordinate value, this can be accomplished in O(n log n) time  Several O(n log n) algorithms for convex hull are known 09-03-2022