Brute-Force Searching and String Matching

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

Brute Force Searching

• A sequential search of a list/array begins at


the beginning of the list/array and continues
until the item is found or the entire list/array
has been searched

1
Sequential Search
bool LinearArrayFind(int array[],int n, int key )
{
for( int i = 0; i < n; i++ )
{
if( array[i] == key )
// Found it!
return true;
}
return false;
}

2
Search Algorithms
Suppose that there are n elements in the array. The following expression
gives the average number of comparisons:

It is known that

Therefore, the following expression gives the average number of comparisons


made by the sequential search in the successful case:

3
Brute-Force String Matching
Example
abacaabaccabacabaabb
abacab
abacab
abacab
abacab
abacab
abacab
abacab
abacab
abacab
abacab
abacab
Example
abacaabaccabacabaabb
abacab
abacab
abacab • The brute force algorithm
abacab • 22+6=28 comparisons.
abacab
abacab
abacab
abacab
abacab
abacab
abacab
• Assume |T| = n and |P| = m
Text T
Pattern P
Pattern P
Pattern P

Compare until a match is found. If so return the index where match


occurs
else return -1
A Brute-Force Algorithm

3 -8
A Brute-Force Algorithm

3 -9
A Brute-Force Algorithm

3 -10
A Brute-Force Algorithm

3 -11
A Brute-Force Algorithm

Time: O(mn) where m=|P| and n=|T|.

3 -12
Brute-Force String Matching
Searching for a pattern, P[0...m-1], in text, T[0...n-1]

Algorithm BFStringMatch(T[0...n-1], P[0...m-1]){


for (i ← 0 to n-m){
j←0
while j < m and P[j] = T[i+j] do
j++
if j = m then return i
}
return -1
}
Time complexity = m(m-n+1) = O(nm)
A bad case
00000000000000001
0000-
0000-
0000-
0000-
0000-
0000-
0000-
0000-
0000-
0000-
0000-
0000-
00001
A bad case
00000000000000001
• 60+5 = 65
0000- comparisons are
0000- needed
0000-
0000- • How many of them
0000- could be avoided?
0000-
0000-
0000-
0000-
0000-
0000-
0000-
00001

You might also like