Professional Documents
Culture Documents
Lecture 78brute Force
Lecture 78brute Force
Lecture # 7&8
Brute Force
Examples:
1. Computing an (a > 0, n a nonnegative integer)
2. Computing n!
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
Analysis of Selection Sort
Stability: yes
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
Examples of Brute-Force String Matching
1. Pattern: 001011
Text:
10010101101001100101111010
2. Pattern: happy
Text: It is never too late
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
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.
Closest-Pair Brute-Force Algorithm (cont.)
• 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
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 (see algorithms in Sec. 5.4)
9 2 7 8
6 4 3 7
C=
5 8 1 8
7 6 9 4