Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP Program for Naive Algorithm for Pattern Searching
PHP (Hypertext Preprocessor) is a widely used server-side scripting language for web development. The Naive algorithm, also known as the Brute Force algorithm, is a simple pattern searching technique that finds occurrences of a pattern within a text by comparing characters one by one.
What is Naive Algorithm?
The Naive algorithm is called "naive" because it doesn't employ sophisticated data structures or advanced techniques. It works by iterating through the text and comparing each character with the corresponding character in the pattern. If a mismatch occurs, it moves to the next position in the text and starts the comparison again.
Algorithm Steps
The Naive algorithm follows these steps
- Start from the first character of the text
- Compare the pattern with the text starting at the current position
- If all characters match, record the starting index
- Move to the next character in the text and repeat
- Continue until the end of the text is reached
PHP Implementation
Here's a complete PHP implementation of the Naive pattern searching algorithm
<?php
function naivePatternSearch($text, $pattern) {
$textLength = strlen($text);
$patternLength = strlen($pattern);
$foundIndexes = array();
// Check each position in text
for ($i = 0; $i <= $textLength - $patternLength; $i++) {
$j = 0;
// Compare pattern with text at current position
while ($j < $patternLength && $text[$i + $j] == $pattern[$j]) {
$j++;
}
// If complete pattern matches, store the index
if ($j == $patternLength) {
$foundIndexes[] = $i;
}
}
return $foundIndexes;
}
// Test the algorithm
$text = "ABAAABABABAAB";
$pattern = "ABA";
$results = naivePatternSearch($text, $pattern);
echo "Text: " . $text . "<br>";
echo "Pattern: " . $pattern . "<br>";
echo "Pattern found at positions: ";
if (!empty($results)) {
echo implode(", ", $results);
} else {
echo "No matches found";
}
?>
Text: ABAAABABABAAB Pattern: ABA Pattern found at positions: 2, 5, 7, 10
Time Complexity
The Naive algorithm has a time complexity of O(m × n), where m is the length of the pattern and n is the length of the text. In the worst case, it may need to check every character of the text against every character of the pattern.
Conclusion
The Naive algorithm provides a straightforward approach to pattern searching in PHP. While it's not the most efficient for large texts, it's easy to understand and implement, making it suitable for educational purposes and small-scale applications.
