ch03n - Bruce Force Algorithms - Edited2
ch03n - Bruce Force Algorithms - Edited2
Brute Force
Brute Force
2. Computing n!
3-1
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 elements.
Generally, on pass i (0 £ i £ n-2), find the smallest element in
A[i..n-1] and swap it with A[i]:
Example: 7 3 2 5
3-2
Analysis of Selection Sort
Stability: yes
3-3
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
3-4
Examples of Brute-Force String Matching
1. Pattern: 001011
Text: 10010101101001100101111010
2. Pattern: happy
Text: It is never too late to have a happy
childhood.
3-5
Pseudocode and Efficiency
Brute-force algorithm
p ¬ 0.0
for i ¬ n downto 0 do
power ¬ 1
for j ¬ 1 to i do //compute xi
power ¬ power * x
p ¬ p + a[i] * power
return p
Efficiency: S0£i£n i = Θ(n^2) multiplications
3-7
Polynomial Evaluation: Improvement
We can do better by evaluating from right to left:
3-8
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
and return the indexes of the points for which the distance
is the smallest.
3-9
Closest-Pair Brute-Force Algorithm (cont.)
3-10
Brute-Force Strengths and Weaknesses
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
3-11
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.
c 7 d
Efficiency: Θ((n-1)!)
3-14
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
3-18
Final Comments on Exhaustive Search
3-19