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
07-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
07-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]:
07-03-2022
Example
07-03-2022
Analysis of Selection Sort
07-03-2022
07-03-2022
Time Efficiency
07-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
07-03-2022
Example
07-03-2022
Code and Example
07-03-2022
Example
07-03-2022
Time Efficiency
07-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
07-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
07-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.
07-03-2022
Example
07-03-2022
Pseudocode and Efficiency Efficiency:
07-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.
07-03-2022
Closest-Pair Brute-Force Algorithm (cont.)
07-03-2022
Analysis
 Basic Operation: Computing Euclidean distance
 Avoid finding square roots
 Now basic operation is squaring the number
07-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
07-03-2022
07-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
07-03-2022
07-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
07-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
07-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
07-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
07-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
07-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
07-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
07-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:
07-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
07-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?
07-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 =
07-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
07-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
07-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
07-03-2022
Solution
07-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
07-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
07-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
07-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
07-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)  ?
07-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.
07-03-2022
Pseudocode of Mergesort
07-03-2022
Pseudocode of Merge
07-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
07-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)
07-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
07-03-2022
Partitioning Algorithm
07-03-2022
Quicksort Example
5 3 1 9 8 2 4 7
07-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)
07-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
07-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)
07-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)
07-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)
07-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
07-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
07-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
07-03-2022
Example of Large-Integer Multiplication
2135  4014
07-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
07-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)
07-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.
07-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.
07-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)!
07-03-2022
Closest Pair by Divide-and-Conquer: Worst Case
The worst case scenario is depicted below:
07-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)
07-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
07-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
07-03-2022

Unit 2

  • 1.
    Unit II BRUTE FORCEAND DIVIDE-AND- CONQUER PART 1 Dr.S.Gunasundari Associate Professor CSE Dept
  • 2.
    Syllabus Brute Force  Computingan  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 07-03-2022
  • 3.
    Brute Force A straightforwardapproach, 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 07-03-2022
  • 4.
    Brute-Force Sorting Algorithm SelectionSort 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]: 07-03-2022
  • 5.
  • 6.
    Analysis of SelectionSort 07-03-2022
  • 7.
  • 8.
  • 9.
    Bubble sort Consecutive adjacentpairs 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 07-03-2022
  • 10.
  • 11.
  • 12.
  • 13.
  • 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 07-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 07-03-2022
  • 16.
    Examples of Brute-ForceString Matching 1. Pattern: 001011 Text: 10010101101001100101111010 1. Pattern: happy Text: It is never too late to have a happy childhood. 07-03-2022
  • 17.
  • 18.
    Pseudocode and EfficiencyEfficiency: 07-03-2022
  • 19.
    Closest-Pair Problem Find thetwo 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. 07-03-2022
  • 20.
  • 21.
    Analysis  Basic Operation:Computing Euclidean distance  Avoid finding square roots  Now basic operation is squaring the number 07-03-2022
  • 22.
    Convex Hull  Theconvex 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 07-03-2022
  • 23.
  • 24.
    Convex Hull BruteForce 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 07-03-2022
  • 25.
  • 26.
    Analysis of ConvexHull 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 07-03-2022
  • 27.
    Brute-Force Strength andWeakness  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 07-03-2022
  • 28.
    Exhaustive Search A bruteforce 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 07-03-2022
  • 29.
    Example 1: TravelingSalesman 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 07-03-2022
  • 30.
    TSP by ExhaustiveSearch 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 07-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
  • 31.
  • 32.
    Example 2: KnapsackProblem 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 07-03-2022
  • 33.
    Knapsack Problem byExhaustive 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: 07-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.
  • 34.
  • 35.
    Example 3: TheAssignment 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? 07-03-2022
  • 36.
    Assignment Problem byExhaustive 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 = 07-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,42+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 07-03-2022
  • 38.
    AssignmentTotal Cost 3,1,2,4 7+6+8+4=25 3,1,4,27+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 07-03-2022
  • 39.
    AssignmentTotal Cost 4,1,2,3 8+6+8+9=31 4,1,3,28+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 07-03-2022
  • 40.
  • 41.
    Final Comments onExhaustive 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 07-03-2022
  • 42.
    Divide-and-Conquer The most-well knownalgorithm 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 07-03-2022
  • 43.
    Divide-and-Conquer Technique (cont.) subproblem2 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 07-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 07-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)  ? 07-03-2022
  • 46.
    Mergesort  Split arrayA[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. 07-03-2022
  • 47.
  • 48.
  • 49.
    Mergesort Example 8 32 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 07-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) 07-03-2022
  • 51.
    Quicksort  Select apivot (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 07-03-2022
  • 52.
  • 53.
    Quicksort Example 5 31 9 8 2 4 7 07-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) 07-03-2022
  • 55.
    Binary Search Very efficientalgorithm 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 07-03-2022
  • 56.
    Analysis of BinarySearch  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) 07-03-2022
  • 57.
    Binary Tree Algorithms Binarytree 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) 07-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) 07-03-2022
  • 59.
    Multiplication of LargeIntegers 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 07-03-2022
  • 60.
    First Divide-and-Conquer Algorithm Asmall 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 07-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 07-03-2022
  • 62.
    Example of Large-IntegerMultiplication 2135  4014 07-03-2022
  • 63.
    Strassen’s Matrix Multiplication Strassenobserved [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 07-03-2022
  • 64.
    Formulas for Strassen’sAlgorithm 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) 07-03-2022
  • 65.
    Analysis of Strassen’sAlgorithm 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. 07-03-2022
  • 66.
    Closest-Pair Problem byDivide-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. 07-03-2022
  • 67.
    Closest Pair byDivide-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)! 07-03-2022
  • 68.
    Closest Pair byDivide-and-Conquer: Worst Case The worst case scenario is depicted below: 07-03-2022
  • 69.
    Efficiency of theClosest-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) 07-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 07-03-2022
  • 71.
    Efficiency of QuickhullAlgorithm  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 07-03-2022