Brute-force search is a problem solving technique which is used to find the solution by systematically enumerating all possible candidates. For example, it can be used for pattern matching. Consider an input string "str" and a search string "p". We will try all possibilities to find whether there's any search string 'p' within the given input string "str".
See Also:
Example program to implement Brute Force Algorithm:
See Also:
C Program To Implement Binary Search
C Program To Implement Linear Search On Sorted & Unsorted Array
C Program To Implement Brute Force Algorithm
C program To Implement Knuth-Morris-Pratt Algorithm
C Program To Implement Linear Search On Sorted & Unsorted Array
C Program To Implement Brute Force Algorithm
C program To Implement Knuth-Morris-Pratt Algorithm
Example program to implement Brute Force Algorithm:
#include <string.h>
#define MAX 100
/* try to find the given pattern in the search string */
int bruteForce(char *search, char *pattern, int slen, int plen) {
int i, j, k;
for (i = 0; i <= slen - plen; i++) {
for (j = 0, k = i; (search[k] == pattern[j]) &&
(j < plen); j++, k++);
if (j == plen)
return j;
}
return -1;
}
int main() {
char searchStr[MAX], pattern[MAX];
int res;
printf("Enter Search String:");
fgets(searchStr, MAX, stdin);
printf("Enter Pattern String:");
fgets(pattern, MAX, stdin);
searchStr[strlen(searchStr) - 1] = '\0';
pattern[strlen(pattern) - 1] = '\0';
res = bruteForce(searchStr, pattern, strlen(searchStr), strlen(pattern));
if (res == -1) {
printf("Search pattern is not available\n");
} else {
printf("Search pattern available at the location %d\n", res);
}
return 0;
}
Output: (Brute Force Search - Example in C)
jp@jp-VirtualBox:~/$ ./a.out
Enter Search String:God is Great
Enter Pattern String:Great
Search pattern available at the location 5
Enter Search String:God is Great
Enter Pattern String:Great
Search pattern available at the location 5
Good information !!! small correction - on string match it must return i instead of j.
ReplyDeleteGood information
ReplyDeletewhat is a plen and slen???
ReplyDeletepattern string length and searched string length
Delete