SlideShare ist ein Scribd-Unternehmen logo
1 von 71
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

Weitere ähnliche Inhalte

Was ist angesagt?

Algorithm chapter 1
Algorithm chapter 1Algorithm chapter 1
Algorithm chapter 1
chidabdu
 
Algorithm chapter 2
Algorithm chapter 2Algorithm chapter 2
Algorithm chapter 2
chidabdu
 

Was ist angesagt? (18)

Greedy Algorithms
Greedy AlgorithmsGreedy Algorithms
Greedy Algorithms
 
5.2 divide and conquer
5.2 divide and conquer5.2 divide and conquer
5.2 divide and conquer
 
algorithm Unit 3
algorithm Unit 3algorithm Unit 3
algorithm Unit 3
 
Algorithm chapter 1
Algorithm chapter 1Algorithm chapter 1
Algorithm chapter 1
 
unit-4-dynamic programming
unit-4-dynamic programmingunit-4-dynamic programming
unit-4-dynamic programming
 
Dynamic programming - fundamentals review
Dynamic programming - fundamentals reviewDynamic programming - fundamentals review
Dynamic programming - fundamentals review
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
 
Backtracking & branch and bound
Backtracking & branch and boundBacktracking & branch and bound
Backtracking & branch and bound
 
Dynamic Programming - Part II
Dynamic Programming - Part IIDynamic Programming - Part II
Dynamic Programming - Part II
 
Divide and Conquer - Part II - Quickselect and Closest Pair of Points
Divide and Conquer - Part II - Quickselect and Closest Pair of PointsDivide and Conquer - Part II - Quickselect and Closest Pair of Points
Divide and Conquer - Part II - Quickselect and Closest Pair of Points
 
algorithm Unit 2
algorithm Unit 2 algorithm Unit 2
algorithm Unit 2
 
5.1 greedy 03
5.1 greedy 035.1 greedy 03
5.1 greedy 03
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
Asymptotic Notation and Data Structures
Asymptotic Notation and Data StructuresAsymptotic Notation and Data Structures
Asymptotic Notation and Data Structures
 
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
 
Design and Analysis of Algorithms
Design and Analysis of AlgorithmsDesign and Analysis of Algorithms
Design and Analysis of Algorithms
 
Algorithm chapter 2
Algorithm chapter 2Algorithm chapter 2
Algorithm chapter 2
 
Analysis of Algorithm
Analysis of AlgorithmAnalysis of Algorithm
Analysis of Algorithm
 

Ähnlich wie Unit 2

Lecture 8 dynamic programming
Lecture 8 dynamic programmingLecture 8 dynamic programming
Lecture 8 dynamic programming
Oye Tu
 
Sienna 4 divideandconquer
Sienna 4 divideandconquerSienna 4 divideandconquer
Sienna 4 divideandconquer
chidabdu
 
Basic MATLAB-Presentation.pptx
Basic MATLAB-Presentation.pptxBasic MATLAB-Presentation.pptx
Basic MATLAB-Presentation.pptx
PremanandS3
 
Seminar Report (Final)
Seminar Report (Final)Seminar Report (Final)
Seminar Report (Final)
Aruneel Das
 

Ähnlich wie Unit 2 (20)

Unit 2
Unit 2Unit 2
Unit 2
 
Perform brute force
Perform brute forcePerform brute force
Perform brute force
 
Cs6402 design and analysis of algorithms may june 2016 answer key
Cs6402 design and analysis of algorithms may june 2016 answer keyCs6402 design and analysis of algorithms may june 2016 answer key
Cs6402 design and analysis of algorithms may june 2016 answer key
 
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
 
Recursive algorithms
Recursive algorithmsRecursive algorithms
Recursive algorithms
 
Lecture 8 dynamic programming
Lecture 8 dynamic programmingLecture 8 dynamic programming
Lecture 8 dynamic programming
 
Sienna 4 divideandconquer
Sienna 4 divideandconquerSienna 4 divideandconquer
Sienna 4 divideandconquer
 
Daa chapter 2
Daa chapter 2Daa chapter 2
Daa chapter 2
 
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...
 
Daa chapter 3
Daa chapter 3Daa chapter 3
Daa chapter 3
 
Basic MATLAB-Presentation.pptx
Basic MATLAB-Presentation.pptxBasic MATLAB-Presentation.pptx
Basic MATLAB-Presentation.pptx
 
Optimising Data Using K-Means Clustering Algorithm
Optimising Data Using K-Means Clustering AlgorithmOptimising Data Using K-Means Clustering Algorithm
Optimising Data Using K-Means Clustering Algorithm
 
Seminar Report (Final)
Seminar Report (Final)Seminar Report (Final)
Seminar Report (Final)
 
Module 2 Design Analysis and Algorithms
Module 2 Design Analysis and AlgorithmsModule 2 Design Analysis and Algorithms
Module 2 Design Analysis and Algorithms
 
Unit 2 in daa
Unit 2 in daaUnit 2 in daa
Unit 2 in daa
 
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)
 
Branch and bound technique
Branch and bound techniqueBranch and bound technique
Branch and bound technique
 

Kürzlich hochgeladen

Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
jaanualu31
 

Kürzlich hochgeladen (20)

Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
 
Computer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersComputer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to Computers
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Rums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdfRums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdf
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Bridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptxBridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptx
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 

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 07-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 07-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]: 07-03-2022
  • 6. Analysis of Selection Sort 07-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 07-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 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-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
  • 18. Pseudocode and Efficiency Efficiency: 07-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. 07-03-2022
  • 21. Analysis  Basic Operation: Computing Euclidean distance  Avoid finding square roots  Now basic operation is squaring the number 07-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 07-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 07-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 07-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 07-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 07-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 07-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 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
  • 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 07-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: 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.
  • 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? 07-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 = 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,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
  • 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 07-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 07-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 07-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 07-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 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 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
  • 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 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 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
  • 53. Quicksort Example 5 3 1 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 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
  • 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) 07-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) 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 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
  • 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 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-Integer Multiplication 2135  4014 07-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 07-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) 07-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. 07-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. 07-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)! 07-03-2022
  • 68. Closest Pair by Divide-and-Conquer: Worst Case The worst case scenario is depicted below: 07-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) 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 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