原创 Bruteforcealgorithm

2006-10-29 16:05 2126 4 4 分类: 软件与OS

Main features


no preprocessing phase;
constant extra space needed;
always shifts the window by exactly 1 position to the right;
comparisons can be done in any order;
searching phase in O(mn) time complexity;
2n expected text characters comparisons.

Description


The brute force algorithm consists in checking, at all positions in the text between 0 and n-m, whether an occurrence of the pattern starts there or not. Then, after each attempt, it shifts the pattern by exactly one position to the right.


The brute force algorithm requires no preprocessing phase, and a constant extra space in addition to the pattern and the text. During the searching phase the text character comparisons can be done in any order. The time complexity of this searching phase is O(mn) (when searching for am-1b in an for instance). The expected number of text character comparisons is 2n.


The C code


void BF(char *x, int m, char *y, int n) {
int i, j;

/* Searching */
for (j = 0; j <= n - m; ++j) {
for (i = 0; i < m && x == y[i + j]; ++i);
if (i >= m)
OUTPUT(j);
}
}



This algorithm can be rewriting to give a more efficient algorithm in practice as follows:


#define EOS '\0'

void BF(char *x, int m, char *y, int n) {
char *yb;
/* Searching */
for (yb = y; *y != EOS; ++y)
if (memcmp(x, y, m) == 0)
OUTPUT(y - yb);
}



The example



First attempt
GCATCGCAGAGAGTATACAGTACG
1234 
GCAGAGAG 

Second attempt
GCATCGCAGAGAGTATACAGTACG
 1 
 GCAGAGAG 

Third attempt
GCATCGCAGAGAGTATACAGTACG
 1 
 GCAGAGAG 

Fourth attempt
GCATCGCAGAGAGTATACAGTACG
 1 
 GCAGAGAG 

Fifth attempt
GCATCGCAGAGAGTATACAGTACG
 1 
 GCAGAGAG 

Sixth attempt
GCATCGCAGAGAGTATACAGTACG
 12345678 
 GCAGAGAG 

Seventh attempt
GCATCGCAGAGAGTATACAGTACG
 1 
 GCAGAGAG 

Eighth attempt
GCATCGCAGAGAGTATACAGTACG
 1 
 GCAGAGAG 

Ninth attempt
GCATCGCAGAGAGTATACAGTACG
 12 
 GCAGAGAG 

Tenth attempt
GCATCGCAGAGAGTATACAGTACG
 1 
 GCAGAGAG 

Eleventh attempt
GCATCGCAGAGAGTATACAGTACG
 12 
 GCAGAGAG 

Twelfth attempt
GCATCGCAGAGAGTATACAGTACG
 1 
 GCAGAGAG 

Thirteenth attempt
GCATCGCAGAGAGTATACAGTACG
 12 
 GCAGAGAG 

Fourteenth attempt
GCATCGCAGAGAGTATACAGTACG
 1 
 GCAGAGAG 

Fifteenth attempt
GCATCGCAGAGAGTATACAGTACG
 1 
 GCAGAGAG 

Sixteenth attempt
GCATCGCAGAGAGTATACAGTACG
 1 
 GCAGAGAG 

Seventeenth attempt
GCATCGCAGAGAGTATACAGTACG
 1 
 GCAGAGAG

The Brute Force algorithm performs 30 character comparisons on the example.

PARTNER CONTENT

文章评论0条评论)

登录后参与讨论
EE直播间
更多
我要评论
0
4
关闭 站长推荐上一条 /3 下一条