Design and Analysis of Algorithms: Dr. Sobia Arshad
Design and Analysis of Algorithms: Dr. Sobia Arshad
Lecture 8
Brute Force
+ “Just do it”
+ Simplest and easiest to apply
+ Widely applicable
- Lower efficiency
Examples
Given:
Text: a (long) string of n characters to search in
Pattern: a (short) string of m characters to search for
Examples:
Text: It is never too late to have a happy life.
Pattern: happy
Text: 10010101101001100101111010
Pattern: 001011
String Matching Example
Pattern: NOT
NOT
NOT
NOT
NOT
NOT
NOT
NOT
String Matching
String Matching
Brute force solution:
1. Align pattern at beginning of text
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
3. while pattern is not found and the text is not yet exhausted,
realign pattern one position to the right and repeat step 2.
String Matching Algorithm
Algorithm StringMatch(T, P)
Input:
An array T[0..n-1] of n characters, representing text
An array P[0..m-1] of m characters, representing pattern
Output:
The position of the first character in the text that starts the first
matching substring if the search is successful and -1 otherwise
public static int search( String text, String pattern)
{
int lengthOfText=text.length();
int lengthOfPattern=pattern.length();
for(int i=0;i<=lengthOfText-lengthOfPattern;i++)
{
int j;
for(j=0;j<lengthOfPattern;j++)
{
if(text.charAt(i+j)!=pattern.charAt(j))
{
break;
}
}
if(j==lengthOfPattern)
return i;
}
return 0;
}
Brute Force Substring Search
TEXT
PATTER
N
Given:
Text: a (long) string of n characters to search in
Pattern: a (short) string of m characters to search for
First iteration
Shift right by one upon mismatch
Second iteration
3rd and 4th Iteration
5th to 7th Iterations
8th to 10th iterations
Final iteration
Problem with Brute Force
Problem with Brute Force
Finally..
String Matching Algorithm
Finding Closest-pair
Brute Force Solution
Closest Pair Algorithm
Efficiency Analysis
Exhaustive Search
A Brute Force technique that tries all possibilities
until a solution is found
is good enough
Exhaustive Search Method
Problem Description:
Given n cities with known distances between each
•Thief
•Transport plane
The Knapsack Problem
Application of Knapsack Problem
This problem often arises in resource
allocation where there are financial
constraints.
The Knapsack Problem
Knapsack by Exhaustive Search
Knapsack Algorithm
Concluding Remarks
Thus, for both the traveling salesman and knapsack
problems considered above, exhaustive search
leads to algorithms that are extremely inefficient on
every input.
Conclusion- Brute Force Approach